I have router with multer-settings -
const express = require('express');
const path = require('path');
const multer = require('multer');
const config = require('config');
const router = express();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'picture_db');
},
filename(req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage,
limits: {
fileSize: 2 * 1024 * 1024
},
fileFilter(req, file, cb) {
const ext = path.extname(file.originalname);
if (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png') {
const err = new Error('Extention');
err.code = 'EXTENTION';
return cb(err);
}
cb(null, true);
}
}).single('file')
router.post('/image',
async(req, res) => {
try {
let status;
upload(req, res, err => {
let error = '';
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') {
error = 'file size';
}
if (err.code === 'EXTENTION') {
error = 'file extention';
}
status = error;
}
});
return res.status(200).json({
msg: status || 'OK',
});
} catch (err) {
return res.status(500).json({
msg: "a"
});
}
}
);
module.exports = router;
And a folder in the project root - picture_db
.
Also I have a postman-query -
Why the picture isn't saving in picture_db
?
I think what you are doing is wrong. When you are uploading your file, you are not naming the key of your file.
Instead, you should add the key in postman to 'file' and upload the file and run it.