admin管理员组

文章数量:1336357

I'm using multer to upload image from the form . but after uploading the image i'm getting Unexpected field error. in my html i'm i have given file and file-model name as 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);
}); 

directive

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

service

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

controller

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

        };

I'm using multer to upload image from the form . but after uploading the image i'm getting Unexpected field error. in my html i'm i have given file and file-model name as 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);
}); 

directive

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

service

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

controller

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

        };
Share Improve this question edited Mar 15, 2016 at 5:16 Ankit asked Mar 15, 2016 at 5:00 AnkitAnkit 5407 silver badges21 bronze badges 1
  • Apart of the problem described in the answer you have another mistake in your code: req.files is for the .any() method, for .single() you should console.log(req.file) not files. – Julio Spinelli Commented Oct 23, 2021 at 13:52
Add a ment  | 

1 Answer 1

Reset to default 8

On the client side you're submitting a file field named file but on the server you expecting a file field named myFile. Change one or the other and it should work.

本文标签: javascriptfile upload with multerError Unexpected fieldStack Overflow