编程语言
首页 > 编程语言> > javascript – 使用multer上传图像的node.js显示未定义

javascript – 使用multer上传图像的node.js显示未定义

作者:互联网

在这里,我正在尝试从2个不同的文件输入上传文件,我可以将其上传到前端,但在后端它仍未定义.尝试了几件事但没有奏效.

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);
}

解决方法:

在nodejs的服务器端无法找到一个文件的情况,即你可以提供multerobject
 / api / v1 / uploadfile“:[{
                方法:“POST”,
                action:controllers.advertController.videoUpload,
                中间件:[multipartMiddleware],
                观点:{
                    json:views.jsonView
                }
            }],

global.multipartMiddleware = multipart();

在服务器端代码在请求的中间件使用multipartMiddleware.

Controller (in this you pass correct parameter to service)

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

Service (if you want to upload multiple file at a time use loop)

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}
       })
    }
 }]);

标签:javascript,angularjs,node-js,express,multer
来源: https://codeday.me/bug/20190706/1396192.html