【发布时间】:2019-04-27 13:46:02
【问题描述】:
我在 Angular.js 的 FormData 上有一些问题
我的代码是这样的:
angular
.module("appFoco", [])
.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]);
});
});
}
};
}])
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file) {
var fd = new FormData();
fd.append('file', file);
$http.post('/send/sendPlanilha', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function() {
})
.error(function() {
});
}
}])
.controller("LoginFormPDF",['$scope','fileUpload', function($scope,fileUpload){
$scope.sendPlanilha = function(){
console.log($scope.email, $scope.nome);
var file = $scope.myFile;
console.dir(file);
$scope.usuario = {"usuarioEmail" : $scope.email, "usuarioNome" : $scope.nome}
fileUpload.uploadFileToUrl(file);
}
}]);
当我执行 $http.post 时,fd.append 上的 fd 是空的,我不知道为什么会发生这种情况。在 fd 上会有一个类似 arq.xls 的文件。
我已经看过很多教程,但没有找到解决方案。 后端代码在 NodeJs 中,所以我需要在 fd.append 上获取一个文件并发送到 $http.post 以获取 Nodejs 上的另一个函数,这个函数如下:
app.post('/send/sendPlanilha', function(req, res, next){}
所以,我的问题是,为什么 fd.append 上的 fd 是空的?我该如何解决这个问题?
【问题讨论】:
-
我认为你的 POST 标头应该是
multipart/form-data -
@AlekseySolovey 将
Content-Type设置为undefined很重要。否则XHR.send 方法将生成不正确的表单数据边界。当XHR.send方法检测到被发送的对象是formData object 时,它将适当地设置Content-Type标头并包含适当的边界。
标签: javascript node.js angularjs