从multer返回未定义的答案

时间:2016-08-31 04:36:26

标签: html angularjs node.js express multer

我在我的nodejs应用程序中使用multer来上传文件。和前端部分的角度。一旦我点击上传图片,在控制台上我得到了未定义的答案。任何人都可以帮我解决问题。 我在这里粘贴代码。 的 server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;

var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
  cb(null,file.originalname);
}
});

var upload = multer({storage: storage});

app.set('views', __dirname + '/views');

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

app.use(express.static('public'));

app.get('/',function(req,res){
    res.render('index',{ title: 'Upload image' });
});

app.post('/loadImage',upload.any(),function(req, res) {
  console.log(req.files);
  console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
   console.log('listening on 8080');
})

这是我的 app.js angularjs代码

var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
        $scope.loadImage = function(){          
  $http.post('/loadImage',$scope.img).success(function(data){
    console.log('Posted successfully');
  }).error(function(data){
    console.error('error');
  })
    };

我的HTML代码:

<form ng-submit="loadImage()" enctype="multipart/form-data">
    <input type="file" name="file" multiple />
    <input type="submit" value="Upload Image" name="submit" />
</form>

在控制台上我得到未定义和内部帖子。在浏览器控制台上我成功发布任何人都可以帮我解决这个问题。我应该获取加载的文件信息,而不是 undefined

2 个答案:

答案 0 :(得分:2)

这是我如何使用Multer上传图片

var multer = require('multer');

exports.loadImage = function (req, res) {
var upload = multer({
        inMemory: true,
        limits: {fileSize: 1024 * 1024 }
    }).single('newPicture');

upload(req, res, function (uploadError) {
    if (uploadError) {
        return res.status(400).send({ message: 'errorUploadingPicture' });
    }
    else {
        var profileImage = 'No data uploaded';
        // this is where the photo data is
        if (req.file && req.file.buffer) {
            profileImage = req.file.buffer;
        }
        return res.json(profileImage );           
    }
});

};

答案 1 :(得分:1)

这是假设您发送文件正确的

尝试

var uploadType = upload.any()

并更改

app.post('/loadImage',upload.any(),function(req, res) {
  console.log(req.files);
  console.log("Inside post");
});

app.post('/loadImage',uploadType,function(req, res) {
  console.log(req.files);
  console.log("Inside post");
});

如果您尝试一次只获取一个文件,那么

var uploadType = upload.single('file')

app.post('/loadImage',uploadType,function(req, res) {
  console.log(req.files);
  console.log("Inside post");
});