We use expressjs framework with multer middleware for handling file upload
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.Implementation
NOTE: Multer will not process any form which is not multipart (multipart/form-data).
+ View file: add enctype="multipart/form-data"
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="imageFile">
<input type="submit">
</form>
+ Create function for filtering file extension.
function fileFilter(req, file, cb){
var extensions = ['png','jpg','jpeg'];
var bool = false;
var extensionFile = getExtension(file);
for(var i=0; i<extensions.length; i++){
if(extensionFile == extensions[i]){
cb(null, true);
bool = true;
}
}
if(!bool) cb(new Error("We support only 'png', 'jpg', jpeg."));
}
function getExtension(file){
return file.originalname.substr(file.originalname.lastIndexOf(".")+1, file.originalname.length);
}
Throw Error |
+ Define upload directory to be store uploaded file.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + "." + getExtension(file));
}
});
var upload = multer({ storage: storage, fileFilter: fileFilter });
+ use middleware to upload url
app.use('/',upload.single('imageFile'), index);
Source Code: download here
Reference: https://www.npmjs.com/package/multer
No comments:
Post a Comment