Uploading multiple images with Multer

0

I have 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 multiple images, and I'm not able to implement. My code is as follows:

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 images from the page? 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>

'

    
asked by anonymous 27.01.2018 / 07:12

2 answers

1

Multer is a very flexible library, for your specific case use the .array () option, this option requires the name of the field and optionally you can define a second argument to limit the number 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 custom filters and settings.

    
27.01.2018 / 09:00
1

Hello, upload multiple files according to lib multer, according to the documentation you must add the files attribute at the time the limits are created, 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 the name attribute in your form must have the same name that you passed in the multer function that in this case would be the 'myImage' Then your form would look like:

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

In your method you check the mimetype and the extension using the file, however when using the multer's array method, you must iterate an array of files that were sent at the time of upload.

    
27.01.2018 / 11:36