In route:
var multer = require('multer');
var storage = multer.diskStorage({
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var imageFilter = function (req, file, cb) {
// accept image files only
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
var upload = multer({ storage: storage, fileFilter: imageFilter})
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: '',
api_key: '',
api_secret: ''
});
app.post('/selleraddproduct/:id', upload.single('image'), (req, res) => {
console.log(req.file);
console.log(req.files);
cloudinary.v2.uploader.upload(req.file.path, function(result) {
// add cloudinary url for the image to the campground object under image property
req.body.productdata.picture = result.secure_url;
});
})
In Front End:
onChangeimage = (event) => {
console.log(event.target.files[0])
this.setState({
picture: event.target.files[0]
})
}
<div className="form-group">
<label htmlFor="inputpicture3" className="col-sm-2 control-label">upload Image</label>
<div className="col-sm-8">
<input type="file" id="inputpicture3" onChange={this.onChangeimage} accept="image/*" placeholder="Image"/>
</div>
</div>