使用Multer

时间:2016-09-06 13:18:44

标签: javascript html express multer

我尝试使用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);
});

4 个答案:

答案 0 :(得分:2)

试试这个 Code 使用 Multer 上传多张图片。

安装包

npm install express multer --save

在 Server.js 中导入依赖项

const express = require('express');
const multer = require('multer');
const path = require('path');

创建 Server.js 文件

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, 'uploads/');
    },
   
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
   
var upload = multer({ storage: storage })
   
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
   
app.post('/', upload.array('multi-files'), (req, res) => {
  res.redirect('/');
});
   
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

创建表单

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>How To Upload Multiple Image Using Multer In Node.js - phpcodingstuff.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Node js Express Multiple Image Upload using Multer Example - Tutsmake.com</h1>
    <form action="/" enctype="multipart/form-data" method="post">
      <input type="file" name="multi-files" accept='image/*' multiple>
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

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

答案 1 :(得分:1)

在这里你可以看到这个例子:

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

的更多信息

答案 2 :(得分:1)

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

答案 3 :(得分:-1)

我的猜测是,对于您要上传的每个文件,请重新点击:

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

如果您这样做,那么在您覆盖之前选择的文件时,只会上传所选的最后一个文件。

要上传多个文件,您必须在文件选择器中一次性选择它们。