Search code examples
javascriptnode.jsexpressmulter

Upload images to Node.js using multer doesn't work


I am trying to upload images to node.js express

  1. bodyParser need a middleware to handle the image file , or it will reply

token undefine

  1. I use Multer as middle ware , as this said, the req.file should hole a array of information, than I can use req.file.image.path to get the file path and other information, than I can save it as a file.

Here is the problem, I upload an image from Postman, I only write console.log(req.file) it shows undefined.

If I try to write req.file.image.path to get the file path, the error is image undefined, it seems like I didn't use multer well, so the req.file didn't hold the data information, Should I create some temp folder to multer or...?

app.js

var  express = require('express')
    ,bodyParser = require('body-parser')
    ,app = express()
    ,multer  =  require('multer')
    ,binary = require('binary')
    ,fs = require('fs')
    ,util= require('util')
    ,http = require('http')
    ,multer = require('multer')
    ,upload = multer({ dest: '/Node/file-upload/uploads/' });

app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies.
app.use(bodyParser.json({limit: '5mb'}));


songs = require('./routes/route');

app.listen(3000, function () {
      console.log('Example app listening on port 3000!');
                          });

app.post('/upload',songs.upload);

route.js

var mongoose = require('mongoose');
var uri = "mongodb://1111:[email protected]:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var binary = require('binary');
var body = require('body-parser');
var fs = require('fs');
var multer = require('multer');

var storage =   multer.diskStorage({
      destination: function (req, file, callback) {
                   callback(null, '/Node/file-upload/uploads/');
                    },
      filename: function (req, file, callback) {
                   callback(null, file.fieldname + '-' + Date.now());
                   }
             });

 var upload = multer({ storage : storage}).single('image');


db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
      console.log("mongodb is connected!!");
      });

exports.upload = function(req, res) {
        upload(req,res,function(err) {
               console.log(req.file);
                 fs.readFile(req.file.image.path, function (err, data){
                      var dirname = "/Node/file-upload/uploads/";
                      var newPath = dirname + req.body.filename;
                 fs.writeFile(newPath, data, function (err) {
                     if(err) {
                         return res.end("Error uploading file.");
                            }
                                 res.end("File is uploaded");
                   });
             });
       });
  };

error

 TypeError: Cannot read property 'image' of undefined
at c:\Users\awei\WebstormProjects\untitled\routes\girlshanlder.js:107:28

Solution

  • You need to set the filename before send the image in the Postman as shown here

    Cheers.