我在nodejs应用程序中使用multer来上传文件。前端部分使用angularjs。单击上传图像后,在控制台上,我得到的答案不确定。谁能帮助我解决问题。
我在这里粘贴代码。
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>


在控制台上,我得到了未定义和内部帖子。在浏览器控制台上,我已经成功发布了,请问有人可以帮助我解决此问题。而不是未定义,我应该获取已加载的文件信息。

最佳答案

这就是我用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 );
    }
});


};

关于html - 从multer返回未定义的答案,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39240825/

10-12 06:35