I'm trying to upload multipart form data using multer. I'm using swagger express middleware for my APIs. Without swagger everything was working. But with swagger, file is not uploaded. There's no validation error, but it simply doesn't upload file. Here's some code that you may want to see:
app.js
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
swaggerExpress.register(app);
var port = 8850;
https.createServer(options, app).listen(port, function () {
console.log('Bus993 server started @ %s!', port);
});
});
upload function
function uploadImage(req, res, multer){
console.log("here", req.files);
//ABOVE SHOWS A VALID FILE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log("fILE", file);
//THIS IS NOT PRINTED
cb(null, '../../public/images');
},
filename: function (req, file, cb) {
console.log(file);
//THIS IS NOT PRINTED
cb(null, file.originalname.replace(/[.]{1}[a-zA-Z]+$/, "") + '_' + moment().format('X') + getExtension(file));
}
});
var upload = multer({storage: storage, fileFilter: fileFilter}).single('imageFile');
upload(req, res, function (err) {
if (err) {
res.status(422).json(
{
status: "error",
data: {error: err.message},
message: "Image upload failed."
}
);
} else {
res.status(200).json(
{
status: "success",
data: "",
message: "Image uploaded successfully."
}
);
}
});
function fileFilter(req, file, cb) {
console.log("fILE", file);
if ((file.mimetype != 'image/jpeg' && file.mimetype != 'image/png' && file.mimetype != 'image/gif') || file.size > 8000) {
cb(new Error('Invalid file.'), false);
} else {
cb(null, true);
}
}
function getExtension(file) {
var res = '';
if (file.mimetype === 'image/jpeg') res = '.jpg';
if (file.mimetype === 'image/png') res = '.png';
if (file.mimetype === 'image/gif') res = '.gif';
return res;
}
}
So, the problem seems that file is undefined here since when I'm using swagger. Earlier it was fine. But now it returns status:success
but image was never uploaded.
Am I doing something wrong?