[英]Append file image to FormData in Javascript (Http Request)
我正面臨着從Ionic / Cordova App,javascript將圖像發布到web api的問題。 我參考鏈接下面的鏈接
這是我的代碼:
$http({
method: "POST",
url: url,
headers: {
//'Content-Type': 'multipart/form-data',
//'Content-Type': false,
//'Content-Type': undefined,
'Cache-Control': 'no-cache',
'DevicePassword': localStorage.getItem("UserPassword"),
'UserName': 'thuong'
},
transformRequest: function (data) {
var formData = new FormData();
formData.append("data", angular.toJson(data.data));
alert("sizeofImg: " + data.files.length);
for (var i = 0; i < data.files.length; i++) {
alert(data.files[i].ImgSrc);
var blob = dataURItoBlob(data.files[i].ImgSrc);
//var file = new File([blob], "file.png",{type: 'image/png');
formData.append("file" + i, blob, "filename" + i + "png");
}
return formData;
},
data: { data: jsonData, files: files }
})
.then(function (result) {
alert("success" + result);
success(result);
},
function (error) {
alert("error" + JSON.stringify(error));
failure(error);
}
);
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
在那里,data.files [i] .ImgSrc是base64 String。 (我使用了Cordova Camera插件來獲取它)它的起點如下:data:image / png; base64,...它始終屬於失敗回調,狀態代碼為:415(UnsupportMediaFile)。我實現了服務器端,如上面的鏈接。 dataURIToBlob方法對嗎? 請幫我。
追加上傳文件見代碼打擊
$scope.updateProfile = function(form_data){
console.log(form_data);
$scope.submitted = true;
$scope.reg = form_data;
var fd = new FormData();
var file = $scope.fileToUpload;
fd.append('file',file);
$http.post(API_URL+"user_update_profile", fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(res){
console.log(res);
})
.error(function(err){
console.log(err);
});
}
注意:fileToUpload變量是文件屬性
var file = $scope.fileToUpload;
fd.append('file',file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.