I am a js-newbie and I am currently trying to use multer to upload some files. Here is my code:
let express = require('express');
let im = require('imagemagick');
let gm = require("gm").subClass({
imageMagick: true
});
let multer = require('multer');
let app = express();
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage}).single('avatar');
app.post('/', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
res.json({
success: false,
message: 'error during uploading'
});
} else if (err) {
res.json({
success: false,
message: 'error during uploading'
});
}
res.json({
success: true,
message: 'Image uploaded'
});
})
})
app.listen(3000);
When I send a post-req with a file (form-data), then I get a success message, however the folder with the file is not created:
EDIT:
I managed to upload the file... I had to change the path of the uploads directory in the code like this:
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
However the uploads directory hast to be created manually, it is not being created automatically if it is missing...how do I solve this problem?
You can check this issue out: https://github.com/expressjs/multer/issues/287
It says you should create a directory in 'destination' or as pre-requirements.