-1
我想將圖片作爲formData的一部分發布到我的客戶端後端API,考慮到API只允許將文件作爲表單數據的一部分發送,而不需要上傳物理文件的URL。下面是我到目前爲止使用的代碼,我也嘗試了一些Angular文件上傳模塊。有角度的文件上傳,但沒有我能找到的幫助我將文件作爲表單數據(多部分/表單數據)的一部分發布,因爲所有人都希望URL能夠上傳物理文件。有人可以幫助我找到一種方式來發布圖片/文件作爲表單數據或告訴我什麼,我在我的代碼中做錯了嗎?在發佈使用謝謝AngularJS用formdata上傳圖片
服務方法:
var deferred = $q.defer();
$http({ method:'POST',
url:'http://localhost/api/clients.php',
data: {
action: 'updateClient',
img: pictureFile
},
transformRequest: angular.identity,
headers: { 'Content-Type': 'multipart/form-data',
'Token': '1234567890'
}
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
return deferred.promise
Form.html
<form name="clientForm">
<fieldset>
<input id="name" type="text" placeholder="Name" ng-model="client.name">
<input type="file" file-model="pictureFile"/>
</fieldset>
<button type="submit" ng-click="updateClient(client, pictureFile)">Submit</button>
</form>
指令
directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
請注意,您不需要延遲。 $ http已經返回一個承諾。你可以簡單地'返回$ http.get(...' –