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>
I’ll try, guys, but I believe it works! Thanks for your help!
– HENNING SUMMER