upload file springboot Required request part 'file' is not present

前端 未结 4 542
感情败类
感情败类 2020-12-14 16:09

I want to add an upload function to my spring boot application; this is my upload Rest Controller

package org.sid.web;

import java.io.BufferedOutputStream         


        
4条回答
  •  猫巷女王i
    2020-12-14 16:42

    Except for other posted answers, the problem might be realated to missing multipart support for the servlet handling the request (spring's DispatcherServlet in case of Spring's app).

    This can be fixed by adding multipart support to dispatcher servlet in web.xml declaration or during initialization (in case of annotation-based config)

    a) web-xml based config

    
    
     
       dispatcher
       
         org.springframework.web.servlet.DispatcherServlet
       
       
         contextConfigLocation
         /WEB-INF/spring/dispatcher-config.xml
       
       1
       
            10485760
            20971520
            5242880
        
     
    
    
    

    b) for annotation-based configuration this would be following:

    public class AppInitializer implements WebApplicationInitializer { 
    
    @Override 
    public void onStartup(ServletContext servletContext) { 
        final AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); 
    
        final ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); 
        registration.setLoadOnStartup(1); 
        registration.addMapping("/"); 
    
        File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));                  
        MultipartConfigElement multipartConfigElement = new  MultipartConfigElement(uploadDirectory.getAbsolutePath(), 100000, 100000 * 2, 100000 / 2); 
    
        registration.setMultipartConfig(multipartConfigElement);
    } }
    

    Then we need to provide multipart resolver which can resolve files sent as multipart-request. For annotation config this can be done in following way:

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

    For xml-based spring configuration you need to add this bean to the context via tag declaration declaration:

     
    

    Alternatively to spring's standard multipart resolver you can use implementation from commons. This way however extra dependency is required:

    
      commons-fileupload
      commons-fileupload
      1.3.3
    
    
    
    
    
    

提交回复
热议问题