使用Angular中的其他字段发送FormData [英] Send FormData with other field in Angular
问题描述
我的表单包含两个输入文本
和一个上传
。我必须将它发送到服务器,但我有一些问题将文件与文本连接。服务器期望这个答案:
I have a form with two input text
and one upload
. I have to send it to the server but I have some problem concatenating the file with the text. The server expects this answer:
"title=first_input" "text=second_input" "file=my_file.pdf"
这是 html :
<input type="text" ng-model="title">
<input type="text" ng-model="text">
<input type="file" file-model="myFile"/>
<button ng-click="send()">
这是控制器:
$scope.title = null;
$scope.text = null;
$scope.send = function(){
var file = $scope.myFile;
var uploadUrl = 'my_url';
blockUI.start();
Add.uploadFileToUrl(file, $scope.newPost.title, $scope.newPost.text, uploadUrl);
};
这是指令 fileModel:
This is the Directive fileModel:
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]);
});
});
}
};
这是调用服务器的服务:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('file', file);
var obj = {
title: title,
text: text,
file: fd
};
var newObj = JSON.stringify(obj);
$http.post(uploadUrl, newObj, {
transformRequest: angular.identity,
headers: {'Content-Type': 'multipart/form-data'}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
如果我尝试发送,我收到错误400,响应是: 多部分表单解析错误 - 多部分中的无效边界:无
。
请求的有效负载是: {title:sadf,text:sdfsadf,file:{}}
If I try to send, I get Error 400, and the response is: Multipart form parse error - Invalid boundary in multipart: None
.
The Payload of Request is: {"title":"sadf","text":"sdfsadf","file":{}}
推荐答案
请勿使用 POST序列化
访问服务器。这样做: FormData
Don't serialize FormData
with POST
ing to server. Do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var payload = new FormData();
payload.append("title", title);
payload.append('text', text);
payload.append('file', file);
return $http({
url: uploadUrl,
method: 'POST',
data: payload,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: { 'Content-Type': undefined},
//prevents serializing payload. don't do it.
transformRequest: angular.identity
});
}
然后使用它:
MyService.uploadFileToUrl(file, title, text, uploadUrl).then(successCallback).catch(errorCallback);
这篇关于使用Angular中的其他字段发送FormData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!