spring-boot的文檔上說javascript
Spring Boot embraces the Servlet 3 javax.servlet.http.Part API to support uploading fileshtml
Servlet 3解決了HttpServletRequest 對文件上傳的支持問題.以前須要藉助commons-upload
完成的事,如今不須要依賴它了.
也就是說,在spring-boot中不能用commons-upload
實現MultipartResolver
接口了,下面這樣定義是錯誤的前端
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
咱們所要作的就是什麼也不作,spring-boot默認就不用commons-upload
了.下面說說具體實現java
文件單獨上傳git
這個只須要用@RequestParam
就能夠了web
upload(@RequestParam MultipartFile file)
文件上傳+表單上傳spring
upload(@ModelAttribute Person person,@RequestParam MultipartFile file)
上傳json(解析)json
upload(@RequestBody Person person)
var xhr=new XMLHttpRequest(); xhr.send(JSON.stringify(data));
前端須要設置Content-type:application/json
mvc
文件上傳+json(不解析)
這個也很簡單app
upload(@RequestParam String person,@RequestParam MultipartFile file)
文件上傳+json(解析)
還想偷下懶,把json裏的屬性塞到Person裏
剛開始想到的是
upload(@RequestBody Person person,@RequestParam MultipartFile file)
可是報415 Unsupported Media Type
,看文檔
上面說的用@RequestPart
,而後json數據能夠經過設置Content-type:application/json
,讓MappingJackson2HttpMessageConverter
識別,把json屬性塞進實體類
問題來了,怎樣才能在multipart/form-data
的分段裏設置Content-type呢?
var form=new FormData(); var file=document.getElementById('file').files[0]; form.append("file",file ); var data={name:"TheViper",age:11}; form.append("person",new Blob([JSON.stringify(data)],{type: "application/json"}));