簡體   English   中英

使用 Multer 在 Nodejs 中上傳多個圖像

[英]Upload multiple image in Nodejs useing Multer

我正在嘗試使用 Multer 上傳多個圖像,但我不斷收到錯誤“TypeError:無法讀取未定義的屬性'文件名'”。 我的代碼適用於單個圖像上傳,但不適用於多個圖像。 我嘗試了幾次調試,但無法找到問題所在。 我想將圖像路徑保存在數據庫中的一列中,格式為:image1,image2,image3.....我是Multer的新手。 我將不勝感激任何幫助。 謝謝。

JS代碼

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代碼(圖片上傳部分)

<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>

單次上傳時,您必須使用:

req.file

但是當上傳張圖片時,您必須使用:

req.files

因為當您要上傳多張照片時,您可以將它們作為數組訪問。

建議和建議:

您可以使用以下 package 上傳您的圖像。 除了上傳之外,您還可以管理圖像的存儲和大小。

多銳化調整器

編輯部分:(用於處理單個和多個圖像示例)

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);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM