I am building a blog builder where i need to upload the image as image is selected on onChange event and that url of uploaded image need to be updated in state.
After post request for image upload . Component gets refreshed automatically and selected file and state is also refreshed.
what to do to stop component from refreshing and the setState to update the correct url of image..
handleChange = async (event) =>
{
event.preventDefault();
if(event.target.name == 'file')
{
var x=event.target.files[0]
var y= event.target.name
let formData = new FormData();
formData.append('file',x)
const response = await axios.post('http://localhost:8009/post/image',formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
})
let {data} = await response
console.log(data)
let file1 = data.name
this.setState({
content:{
key:uuid(),
name:y,
file:file1,
content:URL.createObjectURL(x)
}
})
}
}
The form for Image is as :
<input type="file" name="file" className="form-control-file" onChange={this.handleChange} required/>
Backend on node :
router.post('/image',(req,res)=>
{
console.log(req)
let file = req.files.file;
filename = Date.now() + '-' + file.name;
file.mv(`./client/public/uploads/${filename}`, (err)=>{
if(err) throw err;
});
console.log(`/uploads/${filename}`);
res.json({name:`/uploads/${filename}`})
})