嘗試像這樣,你將被罰款:
$scope.uploadMultipart = function(file, jsonObject, uploadUrl){
var formData = new FormData();
formData.append('json',JSON.stringify(jsonObject));
formData.append('file', file);
return $http({
url: uploadUrl,
method: 'POST',
data: formData,
headers: { 'Content-Type': undefined},
transformRequest: angular.identity
});
};
我不會推薦它,但多數民衆贊成你怎麼可以將文件添加爲一個JSON對象的一部分。通過這種方式,您可以發佈內容類型application/json
。
$scope.uploadHack = function(file, jsonObject, uploadUrl){
var aReader = new FileReader();
aReader.readAsText(file, "UTF-8");
aReader.onload = function (evt) {
//append file to json as raw data
jsonObject.file = {
content: aReader.result,
name: file.name,
size: file.size
};
$http({
url: uploadUrl,
method: 'POST',
data: jsonObject,
headers: { 'Content-Type': 'application/json'},
transformRequest: angular.identity
});
}
};
來源
2017-02-20 10:08:11
lin
是的。這裏我們將追加一個stringifyed的json到multipart。有沒有相反的方式? JSON中的多部分? –
@AmirSuhail爲什麼要這樣做?即使是後端處理(JSON.parse),使用這種多部分結構也更容易 - https://en.wikipedia.org/wiki/KISS_principle – lin
是的。但後端在獲得多部分時不得不調用某些服務。如果我們做到上述那樣,數據將作爲多部分參數,而不是作爲請求主體。要獲取請求正文中的數據,我需要這樣做。 –