我已经用一个简单的 Spring 后端测试了你的代码,它工作正常:
@Controller
public class FileController {
@ResponseBody
@RequestMapping(value = "/data/fileupload", method = RequestMethod.POST)
public String postFile(@RequestParam(value="file", required=false) MultipartFile file,
@RequestParam(value="data") Object data) throws Exception {
System.out.println("data = " + data);
return "OK!";
}
}
我已将您的客户端代码与 angular v1.1.5 一起使用:
var test = {
description:"Test",
status: "REJECTED"
};
var fd = new FormData();
fd.append('data', angular.toJson(test));
//remove comment to append a file to the request
//var oBlob = new Blob(['test'], { type: "text/plain"});
//fd.append("file", oBlob,'test.txt');
return $http.post('/data/fileupload', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
请求如下所示(从 Chrome 控制台网络选项卡复制):
Request URL:http://localhost:8080/data/fileupload
Request Method:POST
Status Code:200 OK
Request Headers
POST /data/fileupload HTTP/1.1
Host: localhost:8080
...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryEGiRWBFzWY6xwelb
Referer: http://localhost:8080/
...
Request Payload
------WebKitFormBoundaryEGiRWBFzWY6xwelb
Content-Disposition: form-data; name="data"
{"description":"Test","status":"REJECTED"}
------WebKitFormBoundaryEGiRWBFzWY6xwelb--
响应 200 OK,控制台输出预期的:{"description":"Test","status":"REJECTED"}