【问题标题】:How to append file on $http.post? [duplicate]如何在 $http.post 上附加文件? [复制]
【发布时间】: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


【解决方案1】:

直接发送file效率更高:

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file) {
       ̶v̶a̶r̶ ̶f̶d̶ ̶=̶ ̶n̶e̶w̶ ̶F̶o̶r̶m̶D̶a̶t̶a̶(̶)̶;̶
       ̶f̶d̶.̶a̶p̶p̶e̶n̶d̶(̶'̶f̶i̶l̶e̶'̶,̶ ̶f̶i̶l̶e̶)̶;̶

       ̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶'̶/̶s̶e̶n̶d̶/̶s̶e̶n̶d̶P̶l̶a̶n̶i̶l̶h̶a̶'̶,̶ ̶f̶d̶,̶ ̶{̶
       return $http.post('/send/sendPlanilha', file, {
          transformRequest: angular.identity,
          headers: {'Content-Type': undefined}
       })
    }
}])

Content-Type: multipart/form-database64 编码增加了 33% 的额外开销。然后后端需要对base64数据进行解码。

【讨论】:

  • 很遗憾无法正常工作,因为 app.post('/send/sendPlanilha', function(req, res, next){} 上的请求正文为空。
猜你喜欢
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 2014-12-13
  • 2010-11-04
  • 1970-01-01
  • 2015-10-15
相关资源
最近更新 更多