1、Http協議傳輸中可以傳送多部分對象集合。對應的Content-Type爲multipart/form-data
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="field1"
Joe Blow
--AaB03x
Content-Disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain
...(file1.txt的數據)...
--AaB03x--
上面爲http請求時傳遞的實體數據,包含兩個不同的對象,字符串field1與文件pics
field1=Joe Blow pics=file1.txt
2、http使用 boundary 字符串來劃分多部分對象集合指明的各類實體。在boundary 字符串指定的各個實體的起始行之前插入“--”標記(例如:--AaB03x、--THIS_STRING_SEPARATES),而在多部分對象集合對應的字符串的最後插入“--”標記(例如:--AaB03x--、--THIS_STRING_SEPARATES--)作爲結束。boundary一般由瀏覽器自動隨機生成。
使用multipart/form-data傳遞數據時一般不設置Content-Type,瀏覽器會設置該首部並帶上生成的boundary,類似於
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzxPPZRJEmGdLBx97
主動設置Content-Type爲multipart/form-data時,會丟掉boundary值,導致後臺無法解析數據。
3、附angularjs與spring boot請求示例
angularjs請求:
$http.post(url,params,{
headers: {
'title': 'boss',
'userId':user.id,
'SESSIONID': user.sessionId,
'Content-Type': undefined
},
transformRequest: angular.identity
}).success(function(data){
if (data.success) {
callback(data);
} else {
toastr.error('交互失敗!');
callback(data);
}
}).error(function() {
toastr.error('請求失敗,請檢查網絡!');
});
SpringBoot代碼:public AjaxResponseMessage addBalance(@RequestParam("file") MultipartFile file,
@RequestParam("accountId") int accountId,
@RequestParam("accountChange") Integer accountChange,
@RequestParam(value = "remarks", required = false) String remarks) {
AjaxResponseMessage ajaxResponseMessage = new AjaxResponseMessage();
try {
ccountService.addBalance(accountId, accountChange, remarks, file);
catch (Exception e) {
ajaxResponseMessage.setSuccess(false);
}
return ajaxResponseMessage;
}