zoukankan      html  css  js  c++  java
  • Spring使用经验之StandardServletMultipartResolver实现文件上传的基本配置

    Note:Spring使用版本是4.1.6.RELEASE

    1. 在实现了AbstractAnnotationConfigDispatcherServletInitializer的类中重载customizeRegistration方法,注册MultipartConfig

    public class ***WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

      @Override
      protected void customizeRegistration(Dynamic registration) {
        registration.setMultipartConfig(new MultipartConfigElement("D:/home/midware/tmp")); // 该目录是临时目录,必须真实存在,不然报500错误
      }

      @Override
      protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MvcConfig.class };
      }

    }

    2. 在实现了WebMvcConfigurerAdapter的类中注册StandardServletMultipartResolver

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = { "***" })
    public class MvcConfig extends WebMvcConfigurerAdapter {

      @Bean
      public ViewResolver irViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/pages/");
        resolver.setSuffix(".jsp");
        resolver.setOrder(10);
        return resolver;
      }

      @Bean
      public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
      }

    }

    3. 实现Upload的业务逻辑的Controller
    @Controller
    public class FileUploadController {

      @RequestMapping(value = "/upload", method = RequestMethod.POST)
      public String upload(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
        System.out.println(file.getContentType());
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("D:/home/midware/upload", file.getOriginalFilename()));// 将上传文件写入到文件系统中
        return "result";
      }

      @RequestMapping(value = "/toupload", method = RequestMethod.GET)
      public String toUpload() {
        System.out.println("forward upload.jsp!");
        return "upload";
      }
    }

    4. 实现upload.jsp的页面,放在webapp/pages/下
    upload.jsp包含以下内容
    <form action="upload" method="post" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" value="Upload" />
    </form>

    5. 其他如web.xml,result.jsp等(略)

  • 相关阅读:
    vscode 整理————开篇之力(一)
    重学c#系列——datetime 和 datetimeoffset[二十一]
    重新点亮shell————什么是shell[一]
    重新整理 .net core 实践篇——— 权限中间件源码阅读[四十六]
    为什么构建容器需要Namespace?
    基于Windows Mobile 5.0的掌上天气预报设计
    使用.NE平台调用服务访问非托管 DLL 中的函数
    .NET Framework 3.0 RC1 开发环境构建
    ASP.NET未处理异常的处理
    基于Silverlight的Windows Phone 推箱子程序开发
  • 原文地址:https://www.cnblogs.com/zjm701/p/6805419.html
Copyright © 2011-2022 走看看