简体   繁体   中英

Upload multiple image in Nodejs useing Multer

I am trying to upload multiple image using Multer but I keep getting error "TypeError: Cannot read property 'filename' of undefined". My code works well for a single image upload but not the multiple. I have tried several debugging but not able to find the issue. I want to save the image path in one column in the database in the format: image1,image2, image3..... I am new to Multer. I will appreciate any assistance. Thanks.

JS code

var multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb){
    cb(null,'./uploads/');
  },
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload
var upload = multer({
  storage: storage,
  limits:{fileSize: 1000000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).array('MyImage', 10);


router.post('/product', function (req, res, next) {
  upload(req, res, (err) => {
  const { prod, MyImage, description} = req.body;

   if(err){
    res.render('product', {
      msg: err
    });
  }
  else {
    db.query("insert into product(prod_name, picture, description) values ('" + prod + "', '" + req.file.filename + "', '" + description + "')", function (err, rs) {
      if (err) {
        console.log(err);
        req.flash('error', 'Error: Product not Inserted')
        res.redirect('/product');
      }
      else {
        req.flash('success_msg', 'Product Successfully Added')
        res.redirect('/product');
      }
    });
  }
  });
});

HTML code (the image upload part)

<form  action="/add_product" method="post" autocomplete="off"  enctype="multipart/form-data">
    <input type="file" id = "files" name = "MyImage" class="hidden" multiple/>
    <label for="files">Choose Image</label>
    <button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>

when single upload you must use:

req.file

but when multiple images upload you must use:

req.files

Because when you want to upload several photos, you have access to them as an array.

Suggestions and recommendations:

You can use the following package to upload your images. In addition to uploading, you can manage the storage and sizing of images.

multer-sharp-resizer

Edit section: (for handle single and multiple images example)

const express = require("express");
const multer = require("multer");

const app = express();

const multerStorage = multer.memoryStorage();

// Filter files with multer
const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image")) {
    cb(null, true);
  } else {
    cb("Not an image! Please upload only images.", false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
});

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  console.log(req.file);
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
  console.log(req.files);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM