I am making API for multiple image uploading in node js. So can you please help me out, how to upload only images and not another file
var Express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var app = Express();
app.use(bodyParser.json());
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Images");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage: Storage }).array("imgUploader", 3); //Field name and max count
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/api/Upload", function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end("Something went wrong!");
}
return res.end("File uploaded sucessfully!.");
});
});
You can add a fileFilter
function to your multer
options. So with a bit of refactoring:
var options = {
storage: multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Images");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
}),
fileFilter: function (req, file, callback) {
const isPhoto = file.mimetype.indexOf("image/") === 0
if (isPhoto) {
callback(null, true) // true if valid
} else {
callback({ message: 'An optional error message'}, false) // false if invalid
}
}
}
And then use these options:
var upload = multer(options).array("imgUploader", 3);
See: https://github.com/expressjs/multer#filefilter
accept="image/*"
on your input will only provide client side validation, and can be removed with the dev console.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments