I'm trying to build a service that allows me to upload files I started with single-file uploading but I have an issue when I try to upload multiple files.
In short, my problem is that if I want to upload more than one image, it appears in the storage folder and I don't see the records in my DB.
Example of single-file upload record
Example of multi-file upload record
But those files are saved on my storage
There are two function in multer:
For single file to upload use:
upload.single('avatar')
For multiple file to upload use:
upload.array('photos', 12) //here 12 is max number of files to upload.
Refer to the following sample code:
const express = require("express");
const multer = require("multer");
const app = express();
const multerStorage = multer.memoryStorage();
// Filter files with multer if you need
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("upload only images.", false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
app.post('/singleUpload', upload.single('avatar'), function (req, res,
next) {
// req.body will hold the text fields, if there were any
console.log(req.file);//req.file is the `avatar` file. here avatar is
input field name
})
app.post('/multipleUpload', upload.array('photos', 12), function (req,
res, next) {
// req.body will contain the text fields, if there were any
// req.files is array of `photos` files.here avatar is
input field name
console.log(req.files);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.