spring mvc注解文件上传下载

需要两个包:

包如何导入就不介绍了,前端代码如下(一定要加enctype="multipart/form-data"让服务器知道是文件上传):

<form action="upload.do" method="post" enctype="multipart/form-data">  
<input type="file" id="upimage" name="file" onchange="setImagePreview()"/> <input type="submit" value="Submit" /></form>

java代码:

 1 import org.apache.commons.io.FileUtils;
 2 import org.springframework.http.HttpHeaders;
 3 import org.springframework.http.HttpStatus;
 4 import org.springframework.http.MediaType;
 5 import org.springframework.http.ResponseEntity;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestParam;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 import org.springframework.web.multipart.MultipartFile;
11 import org.springframework.ui.Model;
12 /**
13  * {@Controller} spring注解,指定此类为controller
14  * {@RequestMapping} 路径
15  * @author v_zweiwang
16  *
17  */
18 @Controller
19 @RequestMapping("/image")
20 public class ImageController {
21     @RequestMapping("/toupload")//用于跳转到上传页面
22     public String toUpload(){
23         return "/WEB-INF/html/upload.html";
24     }
25 
26     @RequestMapping("/upload")
27     public String upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) {
28         SimpleDateFormat dateformat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SS"); //格式化时间    
29         /**构建图片保存的目录**/    
30         String upTime =dateformat.format(new Date()); //用于区别保存
31         String path=request.getSession().getServletContext().getRealPath("/");//获取项目在服务器的绝对路径file C:....webApp/ =url http://...webApp/ 不明白就打印path
34         String fileName = file.getOriginalFilename(); //获得文件名
35         String filePath="/upload/"+upTime+"/";//文件相对路径
36         File targetFile = new File(path+filePath,fileName); //新建一个文件
37         if(!targetFile.exists()){  
38             targetFile.mkdirs();
39         }  
40   
41         //保存  
42         try {  
43             file.transferTo(targetFile); 
44         } catch (Exception e) {  
45             e.printStackTrace();  
46         }  
47         System.out.println(request.getContextPath()+filePath+fileName);  
48         return "redirect:/image/download.do?filepath="+filePath+fileName;//直接重定向下载图片
49     }
50     
51     @RequestMapping("download")  
52     public ResponseEntity<byte[]> download(HttpServletRequest request,String filepath) throws IOException {  
53         String path=request.getSession().getServletContext().getRealPath("/")+filepath;//获取图片路径 filepath为图片相对路径
54         System.out.println(path);
55             File file=new File(path); 
56             HttpHeaders headers = new HttpHeaders();    
57             String fileName=new String("filescan.png".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
58             headers.setContentDispositionFormData("attachment", fileName); //下载后显示的名字
59             headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
60             return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
61                                               headers, HttpStatus.CREATED);  //向浏览器发送数据
62     } 
63 }
原文地址:https://www.cnblogs.com/v-weiwang/p/4786704.html