想使用vue-resource表單提交方式到spring,這個表單中包含json對象和file對象。vue
將json對象和file對象都放到表單提交方式裏面的Request Payload
中,並在Request Payload
中指定內容格式。java
Java實現git
@RequestMapping(value = "/submit", method = RequestMethod.POST, consumes = {"multipart/form-data"}) @ResponseBody public ResponseEntity submit(@RequestPart("file") MultipartFile file,@RequestPart("form") Form form) { ... }
Spring啓用multipart: Spring的配置文件中,啓用以下配置: 主要是添加,這一行:github
<!--讓Servlet支持文件上傳--> <multipart-config/>
<!--配置文件上傳--> <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"> </bean>
web.xml中,對spring的DispatcherServlet進行配置:web
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <!--配置DispatcherServlet--> <servlet> <servlet-name>my-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--讓Servlet支持文件上傳--> <multipart-config/> <!--springMVC須要加載的文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>my-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Javascript實現spring
var formData = new FormData(); formData.append("file", document.forms[formName].file.files[0]); formData.append("form", new Blob([JSON.stringify(this.form)], { type: "application/json" })); this.$http.post("../formdata/submit", formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(function(response) { }, function(response) { // error callback });
這樣就可使用原始的form表單提交了。json
vue和spring很配。spring-mvc
參考: Spring MVC Multipart Request with JSON How can i send vue resource POST with multipart/form-data SpringMVC文件上傳模塊失敗mvc