My current implementation is as follows:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images/items/')
},filename: function (req, file, cb) {
let ext = '';
if (file.originalname.split(".").length>1)
ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
cb(null, Date.now() + ext)
}
})
...Using route....
app.post('/updateItemImage', upload.single('image'), function (req, res, next) {
console.log('user: ' + req.user.id + ' updating image: ' + req.body.item_id);
})
..Alright. That works. req.body.item_id is present in my route, and multer handles req.file, saving it to disk with a unique filename.
however...
I'd like the item to be saved using multer, only if req.user.id and req.body.item_id have certain values. req.body.item_id is undefined within the scope of:
filename: function (req, file, cb) {
So I can't move my code into this function.
TLDR: post function needs to capture req.body.item_id, and req.file. If req.body.item_id == value than save file and res.send('ok') There's more than one way to skin a cat. What's an option that would work?
EDIT: here is the frontend js:
$scope.uploadFile = function(files) {
var fd = new FormData();
var uploadUrl = '/updateItemImage';
var fd = new FormData();
fd.append("image", files[0]);
fd.append("item_id", '11');
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
if (response.data == 'ok') {
return
}
alert('something went wrong')
})
}
EDIT: Swapping the order of parameters so that the body param was first: fd.append("item_id", '11'); fd.append("image", files[0]);
Resolved my issue. This shouldn't matter!
req.body.item_id is undefined within the scope of:
filename: function (req, file, cb) {
I've already tested it, it worked, the value is not undefined
in that scope