Upload multiple images with Multer

Asked

Viewed 1,739 times

1

I’m having a problem uploading multiple images with Multer. I saw that it has attributes like ANY, SINGLE and ARRAY. I can use SINGLE to send a single image, however I need to use several images, and I’m not able to implement. My code is this:

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

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

// Init Upload
const upload = multer({
storage: storage,
limits: { fileSize: 40000 },
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
}).single('myImage');

// Check File Type
function checkFileType(file, cb) {
// Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
// Check ext
const extname = 
filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);

if (mimetype && extname) {
    return cb(null, true);
} else {
    cb('Error: Images Only!');
}
}

// Init app
const app = express();

// EJS
app.set('view engine', 'ejs');

// Public Folder
app.use(express.static('./public'));

app.get('/', (req, res) => res.render('index'));

app.post('/upload', (req, res) => {
upload(req, res, (err) => {
    if (err) {
        res.render('index', {
            msg: err
        });
    } else {
        if (req.file == undefined) {
            res.render('index', {
                msg: 'Nenhum Arquivo Selecionado!'
            });
        } else {
            res.render('index', {
                msg: 'Arquivo(s) Enviados',
                file: `uploads/${req.file.filename}`
            });
        }
    }
    });
    });

How can I get multiple page images? My front is this:

<h4 class="center">Processar Imagem</h4>
<div class="row col s6 offset-s4 center ajuste">
  <%= typeof msg != 'undefined' ? msg : '' %>
    <form action="/upload" method="POST" enctype="multipart/form-data">
      <div class="file-field input-field offset-s4">
        <div class="btn gradient-45deg-blue-indigo">
          <span id="total">Arquivo(s)</span>
          <input type="file" id="files" name="myImage[]" multiple />

        </div>

        <div class="file-path-wrapper">
          <input class="file-path validate" type="text" placeholder="Escolha um ou 
        mais imagens">
        </div>
      </div>
      <output id="list"></output>

      <button class="btn btn-success waves-effect waves-light gradient-45deg- 
        blue-indigo" id="enviar" type="submit" name="action">Enviar<i 
        class="material-icons left">send</i>
        </button>

    </form>
    <br>

    <img src="<%= typeof file != 'undefined' ? file : ''%>" class="responsive-img" alt="">
</div>


<div class="row">

  <output id="list"></output>

</div>

2 answers

1


Multer is a very flexible library, for your specific case use the option .array(), this option requires the field name and can optionally set a second argument to limit the amount of files.

Something basic would be like:

const storage = multer.diskStorage({
    // destino
    destination: function (req, file, cb) {
        cb(null, './public/uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
//
const upload = multer({ storage: storage });
// na rota com limite de 10 arquivos
app.post("/upload", upload.array("myImage[]", 10), function (req, res) {
    console.log('files', req.files);
});

Try the basics and then start adding your filters and custom settings.

  • I’ll try, guys, but I believe it works! Thanks for your help!

1

Hello, upload multiple files as per lib multer, as the documentation you should add the attribute files at the time of the creation of the Limits, your code would look like this/:

    // Init Upload
    const upload = multer({
    storage: storage,
    limits: { fileSize: 40000, files: 10 },//supondo que o máximo seriam 10 arquivos
    fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
    }
    }).array('myImage');

then in your html attribute name in your form must have the same name you passed in the multer function that in this case would be the 'myimage' Then your form would be:

     <input type="file" id="files" name="myImage" multiple />

In your method you check the mimetype and extension using the file, but when using the multer array method, you should iterate an array of files that were uploaded.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.