I\'m trying to upload a file from a HTML form using Express.js and Multer. I\'ve managed to save the file to the desired location (a folder named uploads).
Howe
Personally I implemented the following solutions, which generates a random name for files and appends the original file extension (I assume that my extension is after the last . )
var path = require('path');
var options = multer.diskStorage({ destination : 'uploads/' ,
filename: function (req, file, cb) {
cb(null, (Math.random().toString(36)+'00000000000000000').slice(2, 10) + Date.now() + path.extname(file.originalname));
}
});
var upload= multer({ storage: options });
router.post('/cards', upload.fields([{ name: 'file1', maxCount: 1 }, { name: 'file2', maxCount: 1 }]), function(req, res, next) {
/*
handle files here
req.files['file1']; //First File
req.files['file2']; //Second File
req.body.fieldNames;//Other Fields in the form
*/
});
In the MULTER
documentation you'll find this:
The disk storage engine gives you full control on storing files to disk.
There are two options available, destination and filename. They are both functions that determine where the file should be stored.
Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.
filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.
Note: Multer will not append any file extension for you, your function should return a filename complete with an file extension.