文件上传之SpringMVC
标签(空格分隔): java spring fileupload
文件上传的前端实现,我们在文件上传的章节中讲述个过了,本例中讲述使用springMVC
实现文件上传,另外,项目管理工具使用maven
。
详细代码请参考:https://coding.net/u/shushanfx/p/FromWebFront/git/tree/master/upload_spring
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shushanfx</groupId>
<artifactId>uploadspring</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>servlet30</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/</contextPath>
</webApp>
<httpConnector>
<port>8888</port>
</httpConnector>
</configuration>
</plugin>
</plugins>
</build>
</project>
注意:
- spring包依赖spring-webmvc、spring-context。
- 除使用springMVC包之外,还需使用common-fileuplod包,否则在处理文件上传时将报错。
- 使用jetty plugin,可以在开发环境中通过
mvn clean jetty:run
启动jetty进程进行测试(jetty配置说明见参考文献)
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
代码分析:
- springMVC在配置url-pattern时需要写成
/
,如果配置成/*
将拦截所以请求,包括jsp(本例中可能看不出来,细心的同学可以mark一下)CharacterEncodingFilter
非必须
applicationServlet.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.shushanfx.uploadspring" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
</beans>
注意:
此处需要使用MultipartResovler,如果缺少该配置,post请求中的body将无法解析为文件。
java代码
package com.shushanfx.uploadspring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
/**
* Created by shushanfx on 2016/7/4.
*/
@Controller
public class UploadController {
@RequestMapping(value = "/upload.php", method = RequestMethod.POST)
public void upload(@RequestParam MultipartFile[] upload, HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<String> fileNames = new LinkedList<String>();
if(upload!=null){
for(MultipartFile file : upload){
String fileName = file.getName();
if(fileName!=null){
fileNames.add(fileName + "|" + file.getOriginalFilename() + "|" + file.getSize());
file.transferTo(new File(file.getOriginalFilename()));
}
}
req.setAttribute("fileNames", fileNames);
}
upload(req, resp);
}
@RequestMapping(value="/upload.php", method = RequestMethod.GET)
public void upload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<form id=\"upload-form\" action=\"upload.php\" method=\"post\" enctype=\"multipart/form-data\">\n" +
" <input type=\"file\" id=\"upload\" name=\"upload\" />\n" +
" <input type=\"submit\" value=\"Upload\" />\n" +
"</form>");
if(req.getAttribute("fileNames")!=null){
out.println("fileNames -> ");
List<String> list = (List<String>) req.getAttribute("fileNames");
for(String item : list){
out.print(item + " ");
}
out.println("<br />");
}
out.println("</body>");
out.println("</html>");
}
}
代码分析
- 定义一个Controll,使用注解方式注入;
- 分别定义GET请求和POST请求的处理方式;
- POST请求通过MutipartFile[]参数获取;
- 解析Multipart参数。
测试
通过使用mvn clean jetty:run
即可运行jetty服务,但是此种方式只能用作为开发调试,不要在生产环境中使用。
在浏览器端访问http://localhost:8888/upload.php。
生产环境
- 打包,执行
mvn clean package
命令(因为clean命令会清楚target文件夹,因此在执行该命令时需要停止jetty进程) - 将target文件夹中的servlet30.war上传至相应的服务器,例如放置在tomcat的webapps下,可以通过http://ip:port/servlet30/upload.php进行访问。
参考文献:
- jetty plugin配置:https://www.eclipse.org/jetty/documentation/9.3.x/jetty-maven-plugin.html
- 史上最全的SpringMVC学习笔记: http://www.imooc.com/article/1392