I used the below method in React
Below is how I created input
<form className={styles.root} noValidate autoComplete="off">
<input
name="avatar_image" // name of input field or fieldName simply
enctype="multipart/form-data"
type="file"
onChange={(event) => {
// console logging selected file from menu
console.log( event.target.files[0] ) // gives first file
// setState method with event.target.files[0] as argument
this.setState(prev => ({...prev, user_image: event.target.files[0]}))
}}
/>
</form>
Below is how I made requests to backend
const formData = new FormData()
formData.append('user_name', this.state.user_name)
formData.append('phone_number', this.state.phone_number)
// now below avatar_image is the fieldName of the image, then comes the file to upload, and the file name in the end
formData.append('avatar_image', this.state.user_image, this.state.user_image.name)
axios.post(utils.baseUrl + '/avatar-uploads/avatar-image-upload', formData, {
onUploadProgress: progressEvent => {
console.log( 'upload progress: ' + Math.round((progressEvent.loaded / progressEvent.total)*100) + '%' )
}
})
.then(function (response) {
// further code
})
.catch(function (error) {
console.log(error);
});
Below is how I handled the backned with multer, including dealing with payload
const image_storage = multer.diskStorage({
destination: path.join(__dirname , '../../assets/images/uploads/avatar_image'),
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
});
// Init Upload
const user_avatar_image_upload = multer({
storage: image_storage,
limits:{fileSize: 2000000}, // 1 mb
fileFilter: function(req, file, cb){
checkFileTypeForUserAvatar(file, cb);
}
}).single('avatar_image'); // this is the fieldName that will be dealt
// Check File Type
function checkFileTypeForUserAvatar(file, cb){
// Allowed ext
let filetypes = /jpeg|jpg|png|gif/;
// Check ext
let extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
let mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: jpeg, jpg, png, gif Images Only!');
}
}
// router.post('/protected-avatar-image-upload', passport.authenticate('jwt', { session: false }), (req, res, next) => {
router.post('/avatar-image-upload', (req, res, next) => {
console.log(req.body) // here the req.body will turn out {}
user_avatar_image_upload(req, res, (err) => {
if(err){
console.log(err)
} else {
if(req.file == undefined){
res.status(404).json({ success: false, msg: 'File is undefined!',file: `uploads/${req.file.filename}`})
} else {
console.log( req.body.user_name ) // here req.body.user_name and others will work
// further code
res.status(200).json({ success: true, msg: 'File Uploaded!',file: `uploads/${req.file.filename}`})
}
}
})
})
Hope this helps how to upload a file using multer, with additional payload being passed so that it can be utilized as well with creating database entries or anything else.