Es fundamental comprender el código bien previamente a usarlo a tu trabajo si tquieres aportar algo puedes dejarlo en los comentarios.
Solución:
Lo que quieres es upload.fields()
:
app.post('/rest/upload',
upload.fields([
name: 'video', maxCount: 1
,
name: 'subtitles', maxCount: 1
]), function(req, res, next)
// ...
Uso de Multer Cargar archivos desde dos campos de formularios separados en páginas diferentes En este ejemplo, tengo dos campos: curriculum vitae e imagen. Currículum vitae en una forma e imagen en otra. Ambos están en páginas separadas. Primeras dependencias de importación
const path = require('path'); // for getting file extension
const multer = require('multer'); // for uploading files
const uuidv4 = require('uuidv4'); // for naming files with random characters
Defina fileStorage y fileFilter:
const fileStorage = multer.diskStorage(
destination: (req, file, cb) => // setting destination of uploading files
if (file.fieldname === "resume") // if uploading resume
cb(null, 'resumes');
else // else uploading image
cb(null, 'images');
,
filename: (req, file, cb) => // naming file
cb(null, file.fieldname+"-"+uuidv4()+path.extname(file.originalname));
);
const fileFilter = (req, file, cb) =>
if (file.fieldname === "resume") else
;
Middleware para multer
app.use(
multer(
storage: fileStorage,
limits:
fileSize:'2mb'
,
fileFilter: fileFilter
).fields(
[
name: 'resume',
maxCount: 1
,
name: 'image',
maxCount: 1
]
)
);
Y luego llama a tus rutas. Es posible que deba agregar protección csrf o autenticación junto con esto para mayor seguridad. Pero esto debería funcionar bien.
If you want to upload multiple files/images from the same form, I have used the below code and it works fine. The path of the image is stored in the database; I will skip the database path and go straight to the upload function and how the fields are passed to the save function.
const path = require('path');
const multer = require('multer');
const storage = multer.diskStorage(
destination: (req, file, cb)=>
if(file.fieldname==="profile")
cb(null, './uploads/profiles/')
else if(file.fieldname==="natid")
cb(null, './uploads/ids/');
else if(file.fieldname==="certificate")
cb(null, './uploads/certificates/')
,
filename:(req,file,cb)=>
if(file.fieldname==="profile")
cb(null, file.fieldname+Date.now()+path.extname(file.originalname));
else if(file.fieldname==="natid")
cb(null, file.fieldname+Date.now()+path.extname(file.originalname));
else if(file.fieldname==="certificate")
cb(null, file.fieldname+Date.now()+path.extname(file.originalname));
);
const upload = multer(
storage: storage,
limits:
fileSize: 1024 * 1024 * 10
,
fileFilter: (req, file, cb) =>
checkFileType(file, cb);
).fields(
[
name:'profile',
maxCount:1
,
name:'natid', maxCount:1
,
name:'certificate', maxCount:1
]
);
function checkFileType(file, cb)
//at the save function
upload(req, res, (err) => {
if (err)
console.log(err);
else {
if (req.file == "undefined")
console.log("No image selected!")
else {
let datecreated = new Date();
let fullnames = req.body.firstname + ' ' + req.body.lastname;
let formatedphone = '';
let phone = req.body.personalphone;
if (phone.charAt(0) == '0')
formatedphone = '+254' + phone.substring(1);
else if ((phone.charAt(0) == '+') && (phone.length > 12 || phone.length <= 15))
formatedphone = phone
let teachers =
"teacherid": teacherid,
"schoolcode": req.body.schoolcode,
"fullnames": fullnames,
"email": req.body.email,
"dateofbirth": req.body.dateofbirth,
"nationalid": req.body.nationalid,
"personalphone": formatedphone,
"profile": req.files.profile[0].path,
"natid": req.files.natid[0].path,
"certificate":req.files.certificate[0].path
connection.query('INSERT INTO teachers SET ?', teachers, (error, results, fields) => {`enter code here`
if (error)
res.json(
status: false,
message: 'there are some error with query'
)
console.log(error);
else console.log("Saved successfully");
Si sostienes alguna desconfianza o capacidad de acrecentar nuestro tutorial puedes ejecutar un exégesis y con mucho placer lo ojearemos.