Multipart檔案上傳出現MissingServletRequestParametErexception疑難排解

使用 Spring Boot 1.4.7 上傳Multipart file時出現MissingServletRequestParametErexception的錯誤訊息Required String parameter ‘file’ is not present…。

首先先了解一下@RequestPart 或 @RequestParam 兩者的差別:

@RequestParam annotation can also be used to associate the part of a “multipart/form-data” request with a method argument supporting the same method argument types. The main difference is that when the method argument is not a String, @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the ‘Content-Type’ header of the request part. @RequestParam is likely to be used with name-value form fields while @RequestPart is likely to be used with parts containing more complex content (e.g. JSON, XML).

基本上Spring Boot上支援multipart檔案上傳接口Controller只需要@RequestPart 或 @RequestParam 配上MultipartFile 類型這樣就夠了,但因為當時還想要限制上傳的檔案大小,因為看起來Spring Boot預設使用的StandardServletMultipartResolver並沒有相關設定的setter,於是改使用CommonMultipartResolver,增加兩個Bean如下:

@Bean
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("utf-8");
    resolver.setMaxInMemorySize(20480);
    resolver.setMaxUploadSize(2048000000);
    return resolver;
}

@Bean
@Order(0)
public MultipartFilter multipartFilter() {
    MultipartFilter multipartFilter = new MultipartFilter();
    multipartFilter.setMultipartResolverBeanName("multipartResolver");
    return multipartFilter;
}

並排除使用Spring Boot的預設Resolver

@SpringBootApplication(exclude = { MultipartAutoConfiguration.class })

將將~完成,前端沒什麼意外的話,這樣就可以正常上傳,也可以擋到檔案上傳大小。

但後來不知為何,開了Spring Redis的連線後,所有的上傳都丟出MissingServletRequestParametErexception這個錯誤。起初以為是不是跟annotation有關、或是前端類型沒傳正確、還是環境安全設定把參數擋掉了,個個碰壁後才發現這個貼文。簡單說明就是CommonMultipartResolver處理multipart後又被Spring Boot裡面的一些內建設定給洗掉了,詳細步驟這邊也不再進一步去了解,但至少知道問題所在— misconfiguration了。

解決方法當然就是把CommonMultipartResolver上述那幾段code都拿掉,檔案大小設定的限制設定其實在application.properties裡面就可以設定了

spring.http.multipart.max-file-size=1MB
spring.http.multipart.max-request-size=10MB

上面的#multipart的參數是給Spring Boot 1.4.X,在1.3.X和1.5.X其實鍵值都不太一樣,這需要注意一下。基本上這樣設定就可以正常上傳了!

 

Leave a Reply

avatar