【问题标题】:file upload with multer, Error: Unexpected field使用 multer 上传文件,错误:意外字段
【发布时间】:2016-03-15 13:45:04
【问题描述】:

我正在使用 multer 从表单上传图片。但上传图片后,我收到了意外的字段错误。在我的 html 中,我将文件和文件模型名称指定为 myFile。

app.js

var express = require('express');
var bodyParser = require('body-parser');
var bodyParser = require('body-parser');
var multer = require('multer');

  http = require("http"),
  fs = require('fs'),
  cors = require('cors');

process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});


var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// cross origin:
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});
// end of cross

var config = require("./app/config.js")();

//Folder config.
app.use(express.static(__dirname + '/app/public/'));
app.use(express.static(__dirname + '/app/public/app/'));

app.get('/', function(req, res) {
  res.sendfile('index.html');
});

var upload = multer({ dest: 'uploads/' })
app.post('/upload',upload.single('myFile'), function(req,res){
console.log(req.files);
})
http.createServer(app).listen(config.port, function() {
  console.log("WDC server listening on port " + config.port + " in " + config.mode + " mode");
  console.log("http://localhost:" + config.port);
}); 

指令

    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('file', file);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
           })

           .success(function(){
           })

           .error(function(){
           });
        }
     }]);

控制器

angular.module('myApp')
  .controller('ContactCtrl',['$scope', 'fileUpload', '$http', '$mdToast', '$animate',
   function($scope, fileUpload, $http, $mdToast, $animate){

   $scope.toastPosition = {
       bottom: true,
       top: false,
       left: false,
       right: true
   };


   $scope.getToastPosition = function() {
       return Object.keys($scope.toastPosition)
           .filter(function(pos) { return $scope.toastPosition[pos]; })
           .join(' ');
   };

      $scope.uploadFile = function(){ 
           var file = $scope.myFile;

           console.log('file is ' );
           console.dir(file);
           if( typeof file === 'undefined' || file === null ){
             $mdToast.show(
              $mdToast.simple()
                .textContent('file not found')
                .position($scope.getToastPosition())
                .hideDelay(5000)
            );
           }
           else{
             $mdToast.show(
              $mdToast.simple()
                .textContent('file uploaded Sucessfully')
                .position($scope.getToastPosition())
                .hideDelay(5000)
            );
           }

           var uploadUrl = '/upload';
           fileUpload.uploadFileToUrl(file, uploadUrl);

        };

【问题讨论】:

  • 除了答案中描述的问题之外,您的代码中还有另一个错误: req.files 用于 .any() 方法,对于 .single() 您应该使用 console.log(req.file ) 不是文件。

标签: javascript angularjs node.js multer


【解决方案1】:

在客户端,您要提交一个名为 file 的文件字段,但在服务器上您需要一个名为 myFile 的文件字段。改变一个或另一个,它应该可以工作。

【讨论】:

  • 哦,是的,我的错...感谢您的时间,这似乎解决了问题。
  • 但是在这里我只得到上传文件夹中的二进制数据,为什么会这样??
  • 你是对的,在客户端的请求中,文件对的表单数据键应该与节点中文件的架构相同
猜你喜欢
  • 2021-08-15
  • 2016-09-03
  • 2016-06-14
  • 2018-04-13
  • 2018-08-12
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多