NodeJS 使用Multer上传多个文件

hs1ihplo  于 2023-04-11  发布在  Node.js
关注(0)|答案(3)|浏览(253)

我正在尝试使用Multer上传多张图片。除了只有一个文件正在上传(最后选择的文件)外,所有工作都与预期相同。
HTML

<form class='new-project' action='/projects' method='POST' enctype="multipart/form-data">
  <label for='file'>Select your image:</label>
  <input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' />
  <span class='hint'>Supported files: jpg, jpeg, png.</span>
  <button type='submit'>upload</button>
</form>

JS

//Define where project photos will be stored
var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, './public/uploads');
  },
  filename: function (request, file, callback) {
    console.log(file);
    callback(null, file.originalname)
  }
});

// Function to upload project images
var upload = multer({storage: storage}).any('uploadedImages');

// add new photos to the DB
app.post('/projects', function(req, res){
  upload(req, res, function(err){
    if(err){
      console.log(err);
      return;
    }
    console.log(req.files);
    res.end('Your files uploaded.');
    console.log('Yep yep!');
  });
});

我觉得我漏掉了一些明显的东西...

编辑

代码我试过以下Syed的帮助:
HTML

<label for='file'>Select your image:</label>
<input type='file' accept='image/*' name='uploadedImages' multiple/>
<span class='hint'>Supported files: jpg, jpeg, png.</span>
<input type="submit" value="uploading_img">

JS

multer = require('multer'),

var upload = multer();

app.post('/projects', upload.array('uploadedImages', 10), function(req, res, err) {
  if (err) {
    console.log('error');
    console.log(err);
  }
  var file = req.files;
  res.end();
  console.log(req.files);
});
njthzxwz

njthzxwz1#

使用Multer上传多个文件

NodeJs代码

设置需要文件存储

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, './images/'))
    },
    filename: function (req, file, cb) {
            cb(null, file.fieldname + '-' + Date.now() + file.originalname.match(/\..*$/)[0])
    }
});

设置上传文件限制验证

const multi_upload = multer({
    storage,
    limits: { fileSize: 1 * 1024 * 1024 }, // 1MB
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            const err = new Error('Only .png, .jpg and .jpeg format allowed!')
            err.name = 'ExtensionError'
            return cb(err);
        }
    },
}).array('uploadedImages', 2)

创建上传的主路由

app.post('/projects', (req, res) => {
    multi_upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
            // A Multer error occurred when uploading.
            res.status(500).send({ error: { message: `Multer uploading error: ${err.message}` } }).end();
            return;
        } else if (err) {
            // An unknown error occurred when uploading.
            if (err.name == 'ExtensionError') {
                res.status(413).send({ error: { message: err.message } }).end();
            } else {
                res.status(500).send({ error: { message: `unknown uploading error: ${err.message}` } }).end();
            }
            return;
        }

        // Everything went fine.
        // show file `req.files`
        // show body `req.body`
        res.status(200).end('Your files uploaded.');
    })
});

监听端口

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

HTML代码

<form id="form_el" class='new-project' action='/projects' method='POST' enctype="multipart/form-data">
    <label for='file'>Select your image:</label>
    <input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' />
    <span class='hint'>Supported files: jpg, jpeg, png.</span>
    <button type='submit'>upload</button>
</form>

JavaScript代码

form_el.addEventListener('submit', async function (e) {
    const files = e.target.uploadedImages.files;
    if (files.length != 0) {
        for (const single_file of files) {
            data.append('uploadedImages', single_file)
        }
    }
});

const submit_data_fetch = await fetch('/projects', {
    method: 'POST',
    body: data
});
6yt4nkrj

6yt4nkrj2#

下面是这个例子:

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

router.post('/projects', upload.array('uploadedImages', 10), function(req, res) {
  var file = req.files;
  res.end();
});
<form action="/projects" method="post" enctype="multipart/form-data">
  <input type="file" name="uploadedImages" value="uploading_img" multiple>
  <input type="submit" value="uploading_img">
</form>

访问以了解有关Multer的更多信息。

b1uwtaje

b1uwtaje3#

我的猜测是,对于每个你想上传的文件,你重新点击:

<input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' />

如果这样做,则只会上载最后选择的文件,因为您会覆盖以前选择的文件。
要上传多个文件,您必须在文件选取器中一次选择所有文件。

相关问题