您的位置:首页 > 编程语言 > Java开发

springMVC教程(九)springMVC的文件上传于下载

2014-06-20 09:26 579 查看
springMVC的文件上传于下载

1、springmvc 文件的上传也是借助于两个工具所以需要添加两个jar
   apache-commons-fileupload.jar
   apache-commons-io.jar
2、在spring-servlet.xml中添加文件上传的处理bean的配置。

<bean
id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property
name="defaultEncoding"value="utf-8"
/><!-- 默认编码 (ISO-8859-1) -->
     <property
name="maxInMemorySize"value="10240"
/><!-- 最大内存大小 (10240) -->
      <property
name="uploadTempDir"value="/temp/"
/><!--(临时文件存储目录)
上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->
      <property
name="maxUploadSize"value="-1"
/><!-- 最大文件大小,-1为无限止(-1) -->
   </bean>
   其中属性<property name="uploadTempDir" value="/temp/" />
   的配置配置的是临时文件目录,spring会将文件先传到临时文件,然后我们再调用对应的API将临时文件写到目标文件。
3、编写上传文件的controller
   3.1上传一个文件
   直接在处理的方法中设置形参@RequestParam("file") CommonsMultipartFile  file
   注意这里的参数必须使用@RequestParam指定。
   然后调用方法file.getFileItem().write(targetFile);将临时文件写出到目标文件。
示例:
/**
    *
上传一个文件
    * @param name
    * @param file
    * @param session
    * @return
    */
   @RequestMapping(value="/upload.do",method=RequestMethod.POST)
   public String fileUpLoad(String name,@RequestParam("file")CommonsMultipartFile 
file,HttpSessionsession){
      if(!file.isEmpty()){
        String path = session.getServletContext().getRealPath("/upload/");
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        File targetFile =
new
File(path,new Date().getTime()+fileType);
        try {
           file.getFileItem().write(targetFile);
        } catch (Exception e) {
           e.printStackTrace();
        }
      }
      return"showData";
   }
   3.2上传多个文件
   上传多个文件时,其实和上传一个文件一样,只是将形参改为@RequestParam("file") CommonsMultipartFile[]  file
   然后我们只需在方法中循环处理这些文件即可。
示例:
/**
    *
上传多个文件
    * @param name
    * @param files
    * @param session
    * @return
    */
   @RequestMapping(value="/mupload.do",method=RequestMethod.POST)
   public String muFileUpLoad(String name,@RequestParam("file")CommonsMultipartFile[] 
files,HttpSessionsession){
      if(files!=null && files.length>0){
        String path = session.getServletContext().getRealPath("/upload/");
        for (CommonsMultipartFile file : files) {
           String fileName = file.getOriginalFilename();
           String fileType = fileName.substring(fileName.lastIndexOf("."));
           File targetFile =
new
File(path,new Date().getTime()+fileType);
           try {
              file.getFileItem().write(targetFile);
           } catch (Exception e) {
              e.printStackTrace();
           }
        }
       
      }
      return"showData";
   }
4、文件下载
   文件下载其实和spring没关系,还是使用最普通的方式实现下载即可,在这里不赘述。

示例:

/**
    *
文件下载
    * @param session
    * @param response
    * @param fileName
    * @param isOnline
    * @throws Exception
    */
   @RequestMapping(value="/downLoad.do",method=RequestMethod.GET)
   publicvoid downLoad(HttpSession session,HttpServletResponseresponse,String fileName,boolean
isOnline)throws Exception{
      String path = session.getServletContext().getRealPath("/upload/")+"\\"+fileName;
      File file = new File(path);
      System.out.println(path);
      if(!file.exists()){
        response.sendError(404,
"您要下载的文件没找到");
        return;
      }
      BufferedInputStream bufIn =
new BufferedInputStream(newFileInputStream(file));
      byte [] buff =
newbyte[1024];
      int len = -1;
      response.reset();
      if(isOnline){
        URL u = new URL("file:///"+path);
        response.setContentType(u.openConnection().getContentType());
        response.setHeader("Content-Disposition",
"inline;filename="+fileName);
       
      }else{
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition",
"attachment;filename="+fileName);
      }
      OutputStream out = response.getOutputStream();
      while((len=bufIn.read(buff))!=-1){
        out.write(buff,0,len);
        out.flush();
      }
      bufIn.close();
      out.close();
   }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mvc spring springmvc web 框架