SpringMVC文件上传和下载

1.导入所需要的jar包 
commons-fileupload-1.3.1.jar 
commons-io-2.4.jar 
2.配置springmvc.xml 使得springMVC有上传功能

  <!-- 配置文件上传 multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxInMemorySize" value="1024000"></property>
</bean>

3:前台上传jsp页面

 <!-- 文件上传 -->
  <form action="upload" method="post" enctype="multipart/form-data">
   上传文件: <input type="file" name= "file"><br>
    文件描述 : <input type="text" name="desc"><br><br>
     <input type="submit" name="Submit">
  </form> <br><br>

4:前台上传成功jsp页面

     <c:if test="${ !empty error }">
        <h4>${error}</h4><br>
     </c:if>  
     <c:if test="${ empty error }">
        <h4>文件上传成功</h4><br>
     </c:if>    
    <a href="http://localhost:8080/xxx/index.jsp">点击这里返回首页</a>

5:Controller处理上传文件

//测试文件上传
@RequestMapping("/upload")
public String  uploadFile(@RequestParam(value="desc",required=false)String desc,HttpServletRequest request,
@RequestParam(required=true,value="file")MultipartFile file,ModelMap model){
if(file.getSize()<=0){
model.addAttribute("error","请选择上传文件");
return "success";
}
String filePath="/upload";
ServletContext servletContext = request.getServletContext();

//获取当前服务器发布项目的位置:比如D://apache-tomcat-7.0.82//webapps//springmvc-2//upload
String realPath = servletContext.getRealPath(filePath);
File newFile =new File(realPath);
if(!newFile.exists()){
newFile.mkdirs();
}

   OutputStream out=null;
     InputStream in=null;
     SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-hh");
     
     //修改上传文件名为=文件名称+时间(年月日)
         try {
out = new FileOutputStream(new File(newFile+"\\"+format.format(new Date())+file.getOriginalFilename()));
in = file.getInputStream();
        IOUtils.copy(in, out);
        out.close();
        in.close();
} catch (Exception e) {
model.addAttribute("error","上传文件失败");
e.printStackTrace();
return "success";
}
return "success";
}

6:测试效果,如下图

SpringMVC文件上传和下载


SpringMVC文件下载


1:下载前台jsp

  <a href="testResponseEntity"> Test ResponseEntity</a>

2:下载后台方法

@RequestMapping("testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
byte [] body =null;
ServletContext servletContext = session.getServletContext();
InputStream resourceAsStream = servletContext.getResourceAsStream("file/abc.txt");
body =new byte[resourceAsStream.available()];
resourceAsStream.read(body);

HttpHeaders head =new HttpHeaders();
head.add("Content-Disposition", "attachment;filename=bac.txt");

HttpStatus status=  HttpStatus.OK;
ResponseEntity<byte[]> ResponseEntity =new ResponseEntity<byte[]>(body, head, status);

return ResponseEntity;
}

备注:该下载方法主要使用了ResponseEntity来下载文件,该类可以*的修改相应头信息,并设置修改状态码。和responseBody注解有几分相似,但是responseBody不能下载文件使用,只能使用返回json或者xml格式使用