Spring上传文件问题

我需要将文件从浏览器上传到服务器。 我使用spring 3.2作为我的web框架。

所以我像这样配置我的应用程序。

1 – 我得到了web.xml

   contextClass org.springframework.web.context.support.AnnotationConfigWebApplicationContext   contextConfigLocation racoonsoft.chaos.settings   org.springframework.web.context.ContextLoaderListener   MyServlet org.springframework.web.servlet.DispatcherServlet  contextConfigLocation   1   MyServlet /   admin/library   

2 – MainConfig类

 @Configuration @Import({WebConfig.class }) public class MainConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public static ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor() { return new ScheduledAnnotationBeanPostProcessor(); } @Bean public static StandardServletMultipartResolver multipartResolver() { StandardServletMultipartResolver resolver = new StandardServletMultipartResolver(); return resolver; } } 

3 – 用于处理分段上传的控制器

 @Controller @MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB maxFileSize=1024*1024*10, // 10MB maxRequestSize=1024*1024*50) public class FileUpload { public static final int UPLOAD_RESULT_OK = 100000; @Autowired BookDao book_dao; @RequestMapping(value = "/admin/library/upload_file", method = RequestMethod.POST) public String saveFiles(@RequestParam("file-file") MultipartFile file) throws IOException { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); return "redirect:caps/total_fail"; } else { return "redirect:caps/total_fail"; } } } 

4 – jsp我放置表单提交文件

 ...
...

当我提交表格时,我得到了一个例外

 org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file-file' is not present org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:202) 

我不明白为什么。 当我删除@RequestParam annotaion时,我调用了我的方法,但文件参数= null。 我的问题是什么?

我通过在spring配置文件中添加以下内容来修复此问题:

  

(我得到的错误是“org.springframework.web.bind.MissingServletRequestParameterException:必需的MultipartFile参数’myFile’不存在

我可以做到

 @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/",100000, 200000, 50000); registration.setMultipartConfig(multipartConfigElement); } 

@ user64141是正确的,但如果使用Java配置而不是xml,请尝试

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

您还需要为您的webapp配置MultipartFilter 。 根据它的Javadoc,它使用MultipartResolver解析多部分请求(但你已经配置了那个)。 您需要将其映射到处理文件上载的Controller的请求路径(的一部分)。

首先,将MultipartFilter添加到web.xml:

  multipartFilter org.springframework.web.multipart.support.MultipartFilter  

接下来,将filter映射到需要接受文件上载的URL(的一部分):

  multipartFilter /admin/library/upload_file