springmvc文件上传和下载
首先你要搭建一个ssm的框架,笔者使用的是maven搭建的框架。
文件上传:
1. 添加依赖:
1 <dependency> 2 <groupId>commons-io</groupId> 3 <artifactId>commons-io</artifactId> 4 <version>2.4</version> 5 </dependency> 6 <dependency> 7 <groupId>commons-fileupload</groupId> 8 <artifactId>commons-fileupload</artifactId> 9 <version>1.2.1</version> 10 </dependency>
2. 在springmvc配置文件中,配置MultipartResolver:
1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 2 <property name="maxUploadSize" value="100000000"/> 3 <property name="defaultEncoding" value="UTF-8"/> 4 </bean>
3. 编写jsp页面:
1 <body> 2 <form action="upload" method="post" enctype="multipart/form-data"> 3 文件:<input type="file" name="file" /><input type="submit" value="上传" /> 4 </form> 5 </body>
4. 编写文件上传处理器:
1 /** 2 * 上传文件测试 3 * 4 * @param file 5 * @param req 6 * @return 7 */ 8 @RequestMapping("/upload") 9 @ResponseBody 10 public Object fileupload(@RequestParam("file") CommonsMultipartFile file) { 11 // 设置上传文件的路径 12 String path = "C:\\Users\\SKYER\\Desktop"; 13 // 获取原始文件名 14 String fileName = file.getOriginalFilename(); 15 try { 16 InputStream is = file.getInputStream(); 17 File folder = new File(path); 18 if (!folder.exists()) 19 folder.mkdirs(); 20 File saveFile = new File(folder, fileName); 21 OutputStream os = new FileOutputStream(saveFile); 22 byte[] buffer = new byte[1024]; 23 int len = 0; 24 while ((len = is.read(buffer)) != -1) 25 os.write(buffer, 0, len); 26 os.close(); 27 is.close(); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } 31 return "success!"; 32 }
文件下载:(在上述文件上传基础上添加代码)
1. jsp页面:
1 <body> 2 <form action="download" method="post"> 3 <input type="hidden" name="fileName" value="154.jpg"> 4 <input type="submit" value="下载文档"> 5 </form> 6 </body>
2. 文件下载处理器:
1 /** 2 * 文件下载测试 3 * 4 * @param fileName 5 * @param req 6 * @param resp 7 * @return 8 */ 9 @RequestMapping("/download") 10 public String downloadFile(String fileName, HttpServletResponse resp) { 11 if (fileName != null) { 12 // 文件所在路径 13 String realPath = "C:\\Users\\Nemo\\Desktop"; 14 File file = new File(realPath, fileName); 15 if (file.exists()) { 16 resp.setContentType("application/force-download"); // 设置强制下载不打开 17 resp.addHeader("Content-Disposition", "attachment;fileName=" + fileName); // 设置文件名 18 byte[] buffer = new byte[1024]; 19 FileInputStream fis = null; 20 BufferedInputStream bis = null; 21 try { 22 fis = new FileInputStream(file); 23 bis = new BufferedInputStream(fis); 24 OutputStream os = resp.getOutputStream(); 25 int i = bis.read(buffer); 26 while (i != -1) { 27 os.write(buffer, 0, i); 28 i = bis.read(buffer); 29 } 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } finally { 33 if (bis != null) { 34 try { 35 bis.close(); 36 } catch (IOException e) { 37 e.printStackTrace(); 38 } 39 } 40 if (fis != null) { 41 try { 42 fis.close(); 43 } catch (IOException e) { 44 e.printStackTrace(); 45 } 46 } 47 } 48 } 49 } 50 return null; 51 }