All the data is being sent to the backend except for the image file. I keep getting req.file is undefined, which prevents data from being stored in the database.
On the server side I have a routes folder with the that handles a new food entry from the user.
const multer = require('multer')
var fs = require('fs')
var 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})
router.route('/add', upload.single('foodImage')).post((req, res) => {
var img = fs.readFileSync(req.body.file.path);
var encode_image = img.toString('base64')
var finalImg = {
contentType: req.file.mimetype,
image: new Buffer(encode_image, 'base64')
}
console.log(finalImg);
// remaining code left out
On the front end I have a form that collects input from user that includes a photo and a text description. This is in a component file.
fileSelectedHandler(e) {
this.setState({
selectedFile: e.target.files[0]
})
}
onSubmit(e) {
const nutrition = {
'calories': calories,
'fat': fat,
'sugar': sugar,
'carbs': carbs,
'cholesterol': cholesterol,
'protein': protein,
'photo': result.foods[0].photo.thumb,
'date': this.state.date,
'description': this.state.description,
'food_list': food_list.toString(),
'foodImage': this.state.selectedFile
}
console.log(nutrition);
axios.post('http://localhost:5000/nutrition/add', nutrition).then(res => console.log(res));
window.location = '/nutrition';
//remaining code hidden
render() {
return (
<div>
<h3>Create New Nutrition Log</h3>
<form onSubmit={this.onSubmit} encType='multipart/form-data'>
<div className="form-group">
<label>Upload food image!</label><br></br>
<input type="file" onChange={this.fileSelectedHandler} name="foodImage"/>
</div>
<div className="form-group">
<label>Description: </label>
<input type="text"
required
className="form-control"
value={this.state.description}
onChange={this.onChangeDescription}
/>
</div>
//remaining code hidden