As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current 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);
Upon sending a post request with a file in form-data, I receive a success message, but the directory to store the file is not created:
EDIT:
I have successfully uploaded the file by modifying the path to 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 needs to be manually created as it is not automatically generated when missing... How can I resolve this issue?