Django-rest framework, React JS, Axios- Post JSON

2020-08-01 06:09发布

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?

1条回答
Emotional °昔
2楼-- · 2020-08-01 07:08

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:

class ArticleForm extends React.Component {
  pickedFile = null; // save the picked file in this

  handleUpolad = event => {
    event.preventDefault();
    this.pickedFile = event.target.files[0];
  }

  handleFormSubmit = event => {
    event.preventDefault();

    let data = new FormData(); // creates a new FormData object
    data.append('title', event.target.elements.title.value);
    data.append('text', event.target.elements.content.value);
    data.append('img', this.pickedFile); // add your file to form data

    Axios.post('http://127.0.0.1:8000/api/', data)
    .then(res=>console.log(res))
    .catch(err=>console.log(err))
  }

  render() {
    // your usual code
  }
}
查看更多
登录 后发表回答