How I can upload image files to the Django_Rest framework using axios I have simple model:
class Article(models.Model):
title = models.CharField(max_length=120)
text = models.TextField()
img = models.ImageField(upload_to='article_images/', blank=True, null=True)
create_time = models.DateTimeField(default=datetime.utcnow, blank=True,
null=True
and simple form in React JS:
class ArticleForm extends React.Component {
state= {
img: undefined
}
handleUpolad =(event)=>{
event.preventDefault();
const img=event.target.files[0];
this.setState({
img:img
})
}
handleFormSubmit = (event)=>{
event.preventDefault();
const title=event.target.elements.title.value;
const content=event.target.elements.content.value;
Axios.post('http://127.0.0.1:8000/api/',{
title:title,
text:content,
}).then(res=>console.log(res))
.catch(err=>console.log(err))
}
render() {
return (
<div>
<Form onSubmit={this.handleFormSubmit}>
<Form.Item label="Title" >
<Input placeholder="input placeholder" name='title' />
</Form.Item>
<Form.Item label="Content" >
<Input placeholder="input placeholder" name='content' />
</Form.Item>
<Form.Item label="Dragger" >
<div className="dropbox">
<input type='file' onChange={this.handleUpolad} name='img'>
</input>
</div>
</Form.Item>
<Form.Item >
<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
</div>
);
}
}
It's work fine when I post only Title and Content. How I can post an image file with this data using Axios?
I think you can take advantage of FormData API.
Also, I don't think you need to add the image in state. You could simply keep it to a class variable. If you set the state- there will be unnecessary re-render. Why not avoid that?
Here is the modified code with some comments: