spring mvc multipart文件上传-1

来源:互联网 发布:nba2k14乔丹动作数据 编辑:程序博客网 时间:2024/05/16 07:12

使用StandardServletMultipartResolver解析器上传文件

package com.mjlf.MVC.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Description;import org.springframework.context.support.ResourceBundleMessageSource;import org.springframework.web.multipart.MultipartResolver;import org.springframework.web.multipart.support.StandardServletMultipartResolver;import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.thymeleaf.spring4.SpringTemplateEngine;import org.thymeleaf.spring4.view.ThymeleafViewResolver;import org.thymeleaf.templateresolver.ServletContextTemplateResolver;import java.io.IOException;/** * Created by a123 on 17/6/1. */@Configuration@EnableWebMvc@ComponentScan("com.mjlf.MVC")public class WebConfig extends WebMvcConfigurerAdapter{ /* multipart 文件上传 */    @Bean    public MultipartResolver multipartResolver() throws IOException{        return new StandardServletMultipartResolver();    }}
package com.mjlf.MVC.config;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.DispatcherServlet;import javax.servlet.MultipartConfigElement;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRegistration;public class AppInitializer implements WebApplicationInitializer {    public void onStartup(ServletContext container) throws ServletException {        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();        ctx.register(WebConfig.class);        ctx.setServletContext(container);        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));        servlet.setLoadOnStartup(1);        servlet.addMapping("/");//文件上传配置        servlet.setMultipartConfig(new MultipartConfigElement("/tmp/webMVC"));    }}
package com.mjlf.MVC.controller;/** * Created by a123 on 17/6/14. */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.RequestPart;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.IOException;/** * 处理文件上传控制类 */@Controller@RequestMapping({"/", "/home"})public class FileUploadController {    @RequestMapping(value = "/upload", method = RequestMethod.POST)    public void home(HttpServletRequest request, HttpServletResponse response, @RequestPart("profilePicture")MultipartFile profilePicture) throws IOException {        File proFile = new File("/tmp/webMVC/"+profilePicture.getOriginalFilename());        if(!proFile.exists()){            proFile.getParentFile().mkdirs();            proFile.createNewFile();        }        profilePicture.transferTo(proFile);        System.out.println(request.getParameter("name"));    }}
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"      xmlns:th="http://www.thymeleaf.org"><head>    <meta charset="UTF-8"/>    <title>Title</title></head><body>    welcome to the page    <span th:text="${message}" />    <form method="post" enctype="multipart/form-data" action="/webMVC/upload">        <input type="file" name="profilePicture" accept="image/jpeg,image/png,image/gif"/>        <input type="text" name="name" value="name"/>        <input type="submit" value="上传"/>    </form></body></html>

使用commonsMultipartResolver解析器上传文件

与上边相似, 只需要更改几个配置就可以实现上传文件

package com.mjlf.MVC.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Description;import org.springframework.context.support.ResourceBundleMessageSource;import org.springframework.core.io.FileSystemResource;import org.springframework.web.multipart.MultipartResolver;import org.springframework.web.multipart.commons.CommonsMultipartResolver;import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.thymeleaf.spring4.SpringTemplateEngine;import org.thymeleaf.spring4.view.ThymeleafViewResolver;import org.thymeleaf.templateresolver.ServletContextTemplateResolver;import java.io.IOException;/** * Created by a123 on 17/6/1. */@Configuration@EnableWebMvc@ComponentScan("com.mjlf.MVC")public class WebConfig extends WebMvcConfigurerAdapter{ /**     * commonsMultipartResolver文件上传配置     * @return     * @throws IOException     */    @Bean    public MultipartResolver multipartResolver() throws IOException{        CommonsMultipartResolver commonsMultipartResolver =  new CommonsMultipartResolver();        commonsMultipartResolver.setUploadTempDir(new FileSystemResource("/tmp/webMVC"));        return commonsMultipartResolver;    }}
package com.mjlf.MVC.config;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.DispatcherServlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRegistration;public class AppInitializer implements WebApplicationInitializer {    public void onStartup(ServletContext container) throws ServletException {        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();        ctx.register(WebConfig.class);        ctx.setServletContext(container);        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));        servlet.setLoadOnStartup(1);        servlet.addMapping("/");//与上边相比,此处不需要配置//      servlet.setMultipartConfig(new MultipartConfigElement("/tmp/webMVC"));    }}
<!--这中上传方式需要依赖一下两个库,否则将会抛出异常java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream--><!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->    <dependency>      <groupId>commons-fileupload</groupId>      <artifactId>commons-fileupload</artifactId>      <version>1.2</version>    </dependency>    <dependency>      <groupId>commons-io</groupId>      <artifactId>commons-io</artifactId>      <version>1.4</version>    </dependency>