【Java Web开发学习】Spring MVC文件上传
【Java Web开发学习】Spring MVC文件上传
转载:https://www.cnblogs.com/yangchongxing/p/9290489.html
文件上传有两种实现方式,都比较简单
方式一、使用StandardServletMultipartResolver
依赖Servlet3.0对Multipart请求的支持,需要MultipartConfigElement配置请求的相关参数
code-base方式
@Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); }
通过MultipartConfigElement配置上传临时路径,上传文件大小,上传请求的大小。
通过重载protected void customizeRegistration(ServletRegistration.Dynamic registration)方法实现,看代码
package cn.ycx.web.config; import java.io.IOException; import java.util.Properties; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletRegistration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { // 将一个或多个路径映射到DispatcherServlet上 @Override protected String[] getServletMappings() { return new String[] {"/"}; } // 返回的带有@Configuration注解的类将会用来配置ContextLoaderListener创建的应用上下文中的bean @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] {RootConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] {ServletConfig.class}; } @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { // 上传文件的临时目录 String location = "/tmp"; // 上传文件的最大容量 long maxFileSize = 3145728; // 请求的最大容量 long maxRequestSize = 3145728; // 上传的最小临界值,大于该值才会被写入文件保存 // int fileSizeThreshold = 0; try { Properties prop = new Properties(); prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("upload.properties")); location = prop.getProperty("temporary.location"); maxFileSize = Long.parseLong(prop.getProperty("max.file.size")); maxRequestSize = Long.parseLong(prop.getProperty("max.request.size")); } catch (IOException e) {} // 文件上传配置 registration.setMultipartConfig(new MultipartConfigElement(location, maxFileSize, maxRequestSize, 0)); // 没有找到处理的请求抛出异常 boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); if(!done) throw new RuntimeException("设置异常(throwExceptionIfNoHandlerFound)"); } }
xml-base方式
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>
web.xml配置DispatcherServlet初始化参数
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> ...省略... <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> <multipart-config> <!--临时文件的目录--> <location>E:/tmp</location> <!-- 上传文件最大3M --> <max-file-size>3145728</max-file-size> <!-- 上传文件整个请求不超过3M --> <max-request-size>3145728</max-request-size> </multipart-config> </servlet> ...省略... </web-app>
方式二、使用CommonsMultipartResolver
依赖 commons-fileupload.jar 和 commons-io.jar。上传临时路径,文件大小都在对象中设置。
code-base方式
@Bean public MultipartResolver multipartResolver() throws IOException { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setUploadTempDir(new FileSystemResource(config.uploadTemporaryLocation())); multipartResolver.setMaxUploadSize(config.uploadMaxFileSize()); multipartResolver.setMaxInMemorySize(0); return multipartResolver; }
xml-base方式
<!-- 上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <!-- 最大内存大小 --> <property name="maxInMemorySize" value="10240"/> <!-- 最大文件大小,-1为不限制大小 --> <property name="maxUploadSize" value="-1"/> </bean>
示例代码:
实现了核心部分仅供参考。
package cn.ycx.web.controller; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; 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.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import cn.ycx.web.config.PropertyConfig; /** * 上传 * @author 杨崇兴 2018-07-09 */ @Controller @RequestMapping("/upload") public class UploadController extends BaseController { /** * 属性配置 */ @Autowired private PropertyConfig config; @RequestMapping(value="/image", method=RequestMethod.POST, produces="application/json;charset=UTF-8") public String image(@RequestParam(value = "imageFile", required = false) MultipartFile multipartFile) { try { String serverPath = config.uploadImageSavePath() + new SimpleDateFormat("yyyy/MM/dd/").format(new Date()); File serverPathFile = new File(serverPath); //目录不存在则创建 if (!serverPathFile.exists()) { serverPathFile.mkdirs(); } String fileName = multipartFile.getOriginalFilename(); multipartFile.transferTo(new File(serverPath + fileName)); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "success"; } }
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>上传</title> </head> <body> <form action="/ycxcode/upload/image" method="post" enctype="multipart/form-data"> <input type="text" name="discription" value="discription"/> <input type="file" name="imageFile"> <input type="submit" value="submit"/> </form> </body> </html>