在寫一個api的接口時,需要調用者上傳文件,類型為:MultipartFile。我在使用postman測試時,服務器報錯:具體的錯誤信息為:
HTTP Status 400 - Required MultipartFile parameter 'files' is not present
type Status report
message Required MultipartFile parameter 'files' is not present
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.57
上網搜了以下原因原來時spring-mvc中沒有配置文件上傳解析器: MultipartResolver。
於是我在spring-mvc.xml的配置文件中加了以下配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上傳文件大小限制為31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
再次請求,依然報了之前的錯誤。我再次上網尋找原因,發現需要在方法參數之前加上@RequestParam注解,並指定參數名稱。代碼如下所示
@RequestMapping(value="/syncAudiencesFile")
@ResponseBody
public boolean syncAudiencesFile(@RequestParam("file") MultipartFile file,Integer audienceId,String tencentId,String userIdType,HttpServletRequest request){
// do something...
}
我的postman請求參數如下:
我在此請求 依然報了400錯誤。於是我把@RequestParam("file") 改為 @RequestParam("files"),請求參數中,文件的key也更改為files。具體參數如下:
這一次請求成功了。。
於是,我把請求參數中的MultipartFile file 中的參數名也更改為files,再次請求又會報400錯誤。
所以總結一下,如果下次在遇到springmvc上傳文件報400,可以嘗試以下:
檢查springmvc配置中有沒有添加文件上傳解析,沒有的話需要加上。(代碼與上面貼的一致,上傳大小限制可以不加)
參數加上@RequestParam("") 並加上名稱,名稱不能方法中的參數名相同。但是要與提交上的數據的key相同。
至於產生這樣錯誤的原理還沒有總結。