1

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:1111@ds061365.mongolab.com: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
mikefrey
  • 4,653
  • 3
  • 29
  • 40
Awei Hsue
  • 257
  • 5
  • 19
  • Can you share with us your html form? – danilodeveloper Feb 25 '16 at 18:25
  • I use postman upload an binary image file , content type set as image/jpeg – Awei Hsue Feb 25 '16 at 18:26
  • Try to change `req.file.image.path` to `req.file.path` (inside the exports.upload block) and have you created the `/Node/file-upload/uploads/` folder? – danilodeveloper Feb 25 '16 at 18:29
  • @danilodeveloper it's the same, if I log req.file , it's undefined ,so I have no idea , I check multer github , there are few people have same issue , have and middle ware for upload recommend ? – Awei Hsue Feb 25 '16 at 18:33
  • From github repo _Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you._ Have you created the dest folder? – danilodeveloper Feb 25 '16 at 18:35
  • @danilodeveloper yes , but not sure it's right , /Node/file-upload/uploads/ , I creat at ( c:/Node/file-upload/uploads/ ) is this right? – Awei Hsue Feb 25 '16 at 18:38
  • in your code, you have 2 `multer = require('multer')`, try to remove the first one and test again. – danilodeveloper Feb 25 '16 at 18:41
  • @danilodeveloper wops, sorry for that , I remove the first one ,it's the same , is the c:/Node/file-upload/uploads = /Node/file-upload/uploads/ ? – Awei Hsue Feb 25 '16 at 18:43
  • The folder is relative to the code of route.js (in your case). can you try to use the [path module](https://docs.nodejitsu.com/articles/file-system/how-to-use-the-path-module) to confirm the folder path and test again? – danilodeveloper Feb 25 '16 at 18:47
  • @danilodeveloper I check it , path is right cause my other api for view photo is the same folder and same path( /Node/file-upload/uploads/),it works fine – Awei Hsue Feb 25 '16 at 18:49
  • Do you set the `content type` when send the request from Postman? If yes, try to remove the `content type` and test again. – danilodeveloper Feb 25 '16 at 18:54
  • @danilodeveloper yes, I try with content type and no content type , all the same , https://github.com/expressjs/multer/issues/203 there are few people happen same issue , upload reply file uploaded , but req.file is undefined – Awei Hsue Feb 25 '16 at 18:57
  • Can you send the upload from a HTML form with multpart? I suspect that you need to have an HTML `` – danilodeveloper Feb 25 '16 at 19:07
  • @danilodeveloper wops...I don't how to do HTML ;( maybe i try from android – Awei Hsue Feb 25 '16 at 19:12
  • Or you can try to set the filename before send the image in the Postman as shown [here](http://stackoverflow.com/questions/16015548/tool-for-sending-multipart-form-data-request) – danilodeveloper Feb 25 '16 at 19:13
  • @danilodeveloper I change file name is the same , just post question to multer github page , hope can get andwer;( – Awei Hsue Feb 25 '16 at 19:16
  • Ok, good luck there :). – danilodeveloper Feb 25 '16 at 19:16
  • @danilodeveloper yo~you are right , in postman , I have to assign a key , same as id = image :D , you can post and answer than I can vote you – Awei Hsue Feb 26 '16 at 04:11

2 Answers2

2

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

Cheers.

Community
  • 1
  • 1
danilodeveloper
  • 3,840
  • 2
  • 36
  • 56
0

Full code for uploading images in your MySQL database and in folder too.

Just define the module and install multer and path and save it.

var multer = require('multer'); 
var path   = require('path');

var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploadimages')
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

app.post('/imginsert',multer({
    storage: storage,
    fileFilter: function(req, file, callback) {
        var ext = path.extname(file.originalname)
        if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') 
                    {
            return callback(res.end('Only images are allowed'), null)
        }
        callback(null, true)
    }
}).single('img'), function(req, res) {
 /*img is the name that you define in the html input type="file" name="img" */       

        var data = {
            table_column_name(your database table column field name) :req.file
        };
        var query = connection.query("Insert into tablename set ?" ,data,function(err, rows)      
        {                                                      
          if (err)
             throw err;
         res.redirect('/blog');
        });
        console.log(query.sql);
        console.log(req.file);
    });
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Y. Joy Ch. Singha
  • 3,056
  • 24
  • 26