I uploaded a photo and it works successfully. But I want to give one more param to the middleware. I pass it but I dont get it. I want to pass the roomID (in my case 40). Its not undefined!.
Where can I caught the room id?
if I console.log req.file then there is no roomIdent. and req.params is empty
But I get all other params like filename type etc...
Nodejs middleware:
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const Storage = multer.diskStorage({
destination(req, file, callback) {
callback(null, './uploads');
},
filename(req, file, callback) {
callback(null, `${file.fieldname}_${Date.now()}_${file.originalname}`)
}
});
module.exports = async (req, res, next) => {
console.log(req.params);
let upload = multer({
storage: Storage
}).single('photo');
upload(req, res, err => {
if(!req.file) {
return res.json({
upload: false,
message: 'Bitte wählen Sie ein Foto oder Video aus.'
});
} else if (err instanceof multer.MulterError) {
return res.json({
upload: false,
message: err
});
} else if (err) {
return res.json({
upload: false,
message: err
});
}
const allowTypes = ['image/jpeg', 'image/jpg' ,'image/png', 'image/webp', 'image/gif'];
// Allowed extension
const extension = path.extname(req.file.originalname);
const anotherExtension = path.extname(req.file.filename);
if(extension == '.jpg' || extension == '.jpeg' || extension == '.png' || extension == '.gif'
|| extension == '.webp') {
if(anotherExtension == '.jpg' || anotherExtension == '.jpeg' || anotherExtension == '.png' || anotherExtension == '.gif'
|| anotherExtension == '.webp') {
if(allowTypes.includes(req.file.mimetype)) {
req.filename = req.file.filename;
next();
}
}
}
});
};
React native fetch :
const upload = async ({localuri, filename, type, roomIdent}) => {
try {
const formData = new FormData();
formData.append('photo', {
uri: localuri,
name: filename,
type,
roomid: roomIdent
});
const options = {
headers: {
'Accept': 'application/json',
'Content-Type':'multipart/form-data'
},
method: 'POST',
body: formData
};
const res = await fetch('http://xxxxx:3000/uploadphoto', options);
const out = await res.json();
return out;
} catch(e) {
return e;
}
};
export default upload;
For RoomID append it like this in formData
const formData = new FormData();
formData.append('photo', {
uri: localuri,
name: filename,
type,
});
formData.append('roomid', roomIdent);
... Now Continue...
Then in backend access it like this
console.log(req.body.roomid) // This will log roomId on console