使用Multer上传图像时,Node.js显示未定义。

4

我将尝试为两个不同的文件输入上传文件,我能够将其上传到前端,但在后端它仍然是undefined。尝试了几种方法,但都没有成功。

HTML:

<input type="file" name="file1" file-model = "file1"/>
<input type="file" name="file2" file-model = "file2"/>
<button  ng-click = "uploadFile()">UPLOAD FILES</button>

指令:

angular.module('myApp').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]);
          });
        });
      }
    };
  }
])

服务:

angular.module('myApp').service('fileUpload', ['$http',
  function($http) {
    this.uploadFileToUrl = function(file, uploadUrl) {
      var fd = new FormData();
      fd.append('file1', file);
      fd.append('file2', file);
      $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {
          'Content-Type': undefined
        }
      })
    }
  }
]);

控制器:

angular.module('myApp')
  .controller('ContactCtrl', ['$scope', 'fileUpload', '$http',
      function($scope, fileUpload, $http) {
        $scope.uploadFile = function() {
          var file1 = $scope.file1;
          var file2 = $scope.file2;
          console.log('file is ');
          console.dir(file1);
          console.dir(file2);

          var uploadUrl = '/upload';
          fileUpload.uploadFileToUrl({
            file1, file2
          }, uploadUrl);
        };

服务器:

function upload(req,res){
  console.log(req.files.file1);
}

console.dir(file1);console.dir(file2); 分别打印什么? - jofftiquez
是的,它会打印输出。 - Ankit
我的意思是它们打印了什么?它们的输出是什么? - jofftiquez
这是我的浏览器控制台读取的内容:文件 lastModified: 1446532932000 lastModifiedDate: Tue Nov 03 2015 12:12:12 GMT+0530 (印度标准时间) 名称: "pic03.jpg" 大小: 76606 类型: "image/jpeg" webkitRelativePath: "" __proto__: Blob - Ankit
安基特·维尔马,恩西格? - null1941
1个回答

1
在Node.js服务器端找不到文件的一种情况是,您可以在/api/v1/uploadfile中提供multer对象:

/api/v1/uploadfile": [{ method: "POST", action: controllers.advertController.videoUpload, middleware: [multipartMiddleware], views: { json: views.jsonView } }],

global.multipartMiddleware = multipart();

在服务器端代码中,使用multipartMiddleware作为请求的中间件。

控制器(在此处传递正确的参数给服务)

var file ={} file.file1=file1; file.file2=file2; fileUpload.uploadFileToUrl(file, uploadUrl);

服务(如果您想一次上传多个文件,请使用循环)

angular.module('myApp').service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
       var fd = new FormData();
       fd.append('file1', file.file1);
       fd.append('file2', file.file2);
       $http.post(uploadUrl, fd, {
          transformRequest: angular.identity,
          headers: {'Content-Type': undefined}
       })
    }
 }]);

1
谢谢你的解决方案,它帮了我很大的忙。我只需要按照你的指示更改服务代码 :) - Ankit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接