springMVC上传和下载附件
上传:
-
导入需要的jar包:Spring MVC类库 + 文件上传下载需要的JAR包,图中A处为文件上传下载需要的JAR包,其余为Spring MVC类库。
- 构建领域模层:model层和control层、view层
FileController:
1 package com.controller.system; 2 3 import java.io.FileOutputStream; 4 import java.io.OutputStream; 5 import java.text.SimpleDateFormat; 6 import java.util.Date; 7 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import javax.servlet.http.HttpSession; 11 12 import org.springframework.stereotype.Controller; 13 import org.springframework.ui.Model; 14 import org.springframework.web.bind.annotation.RequestMapping; 15 import org.springframework.web.bind.annotation.RequestMethod; 16 import org.springframework.web.multipart.MultipartHttpServletRequest; 17 import org.springframework.web.multipart.commons.CommonsMultipartFile; 18 19 import com.model.system.MyFile; 20 21 @Controller 22 @RequestMapping("fileController") 23 public class FileController { 24 25 @RequestMapping(value = "/upload.do", method = RequestMethod.POST) 26 public String upload(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model,MyFile myFile) { 27 28 try { 29 // 1. 转化request 30 MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request; 31 // 2. /获得文件 32 CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("myUpFile");//myUpFile前端页面输入附件处input的name 33 // 3. 获得文件的字节数组 34 byte[] bytefile = cfile.getBytes(); 35 // 4. 获得文件后缀名 36 String oldName = cfile.getOriginalFilename(); 37 // 截取后缀名 38 String suffix = oldName.substring(oldName.lastIndexOf(".")); 39 // 5. 获取项目的路径 40 String path = request.getSession().getServletContext().getRealPath("/"); 41 // 6. 定义OutputStream 42 // 设置文件名:取当前时间 43 Date date = new Date(); 44 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 45 String filename = sdf.format(date); 46 47 String url = "\\G:\\upanddown\\upfile\\" + filename + suffix; 48 System.out.println(url); 49 OutputStream os = new FileOutputStream(url); 50 51 os.write(bytefile); 52 // 7.关闭资源 53 os.flush(); 54 os.close(); 55 } catch (Exception e) { 56 e.printStackTrace(); 57 } 58 return "upload"; 59 60 } 61 }
MyFile
1 package com.model.system; 2 3 public class MyFile { 4 5 private String fileUserName; 6 private String url; 7 8 9 public MyFile() {} 10 11 public MyFile(String fileUserName, String url) { 12 super(); 13 this.fileUserName = fileUserName; 14 this.url = url; 15 } 16 17 public String getFileUserName() { 18 return fileUserName; 19 } 20 21 public void setFileUserName(String fileUserName) { 22 this.fileUserName = fileUserName; 23 } 24 25 public String getUrl() { 26 return url; 27 } 28 29 public void setUrl(String url) { 30 this.url = url; 31 } 32 33 @Override 34 public String toString() { 35 return "MyFile [fileUserName=" + fileUserName + ", url=" + url + "]"; 36 } 37 38 39 }
-
设置上传页面upload的表单
- 配置web.xml和dispatcher-servlet.xml
web.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 3 <display-name>springMvc_upload</display-name> 4 <servlet> 5 <servlet-name>dispatcher</servlet-name> 6 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 7 </servlet> 8 <servlet-mapping> 9 <servlet-name>dispatcher</servlet-name> 10 <url-pattern>*.do</url-pattern> 11 </servlet-mapping> 12 <filter> 13 <filter-name>CharacterEncodingFilter</filter-name> 14 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 15 <init-param> 16 <param-name>encoding</param-name> 17 <param-value>UTF-8</param-value> 18 </init-param> 19 </filter> 20 <filter-mapping> 21 <filter-name>CharacterEncodingFilter</filter-name> 22 <url-pattern>/*</url-pattern> 23 </filter-mapping> 24 <welcome-file-list> 25 <welcome-file>upload.jsp</welcome-file> 26 </welcome-file-list> 27 </web-app>
dispatcher-servlet.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/mvc 9 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context-3.0.xsd 12 http://www.springframework.org/schema/aop 13 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 14 http://www.springframework.org/schema/tx 15 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> 16 17 <!-- 注解驱动 --> 18 <mvc:annotation-driven /> 19 <!-- springMVC扫描驱动 --> 20 <context:component-scan base-package="com.controller.*"></context:component-scan> 21 22 <!-- 配置试图解析器 --> 23 <bean 24 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 25 <property name="prefix" value="/"></property> 26 <property name="suffix" value=".jsp"></property> 27 </bean> 28 29 <!-- 从请求和响应读取/编写字符串 --> 30 <bean id="stringConverter" 31 class="org.springframework.http.converter.StringHttpMessageConverter"> 32 <property name="supportedMediaTypes"> 33 <list> 34 <value>text/plain;charset=UTF-8</value> 35 </list> 36 </property> 37 </bean> 38 39 <!-- 用于将对象转换为 JSON --> 40 <bean id="jsonConverter" 41 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> 42 <bean 43 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 44 <property name="messageConverters"> 45 <list> 46 <ref bean="stringConverter" /> 47 <ref bean="jsonConverter" /> 48 </list> 49 </property> 50 </bean> 51 52 <!-- 上传下载配置 --> 53 <bean id="multipartResolver" 54 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 55 <!-- maxUploadSize:文件上传的最大值以byte为单位 --> 56 <property name="maxUploadSize" value="1024000"></property> 57 </bean> 58 59 60 </beans>
下载:
配置和上面的一样(用同一个项目),在view层中编码如下,用来下载:
1 <body> 2 <h1>文件中心</h1> 3 ${myFile} 4 <a href="<%=basePath%>fileController/download.do?url=${myFile.url}" >下载</a> 5 </body>
FileController:中添加下载方法:
1 /** 2 * 下载文件 3 * @throws IOException 4 */ 5 6 @RequestMapping(value = "/download.do") 7 public void download(HttpServletRequest request,HttpServletResponse response, String url) throws IOException { 8 String strUrl = url; 9 10 // 截取字符串 11 int i = 29; 12 String urlstr = url.substring(i); 13 System.out.println("#########################___" + urlstr); 14 15 // 获取输入流 16 InputStream bis = new BufferedInputStream(new FileInputStream(new File( 17 strUrl))); 18 // 假如以中文名下载的话 19 String filename = urlstr; 20 // 转码,免得文件名中文乱码 21 filename = URLEncoder.encode(filename, "UTF-8"); 22 // 设置文件下载头 23 response.addHeader("Content-Disposition", "attachment;filename=" 24 + filename); 25 // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 26 response.setContentType("multipart/form-data"); 27 BufferedOutputStream out = new BufferedOutputStream( 28 response.getOutputStream()); 29 int len = 0; 30 while ((len = bis.read()) != -1) { 31 out.write(len); 32 out.flush(); 33 } 34 out.close(); 35 }