Django-rest框架,React JS,Axios-发布包含图像文件的JSON数据 [英] Django-rest framework, React JS, Axios- Post JSON data which contains image file

查看:109
本文介绍了Django-rest框架,React JS,Axios-发布包含图像文件的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 axios 将图像文件上传到 Django_Rest 框架 我有一个简单的模型:

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

React JS中的简单形式:

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>
      );
    }
  }

仅发布标题和内容时,效果很好.如何使用 Axios 将带有此数据的图像文件发布?

It's work fine when I post only Title and Content. How I can post an image file with this data using Axios?

推荐答案

我认为您可以利用此外,我认为您无需在状态中添加图片.您可以简单地将其保留在类变量中.如果设置状态-将没有不必要的重新渲染.为什么不避免呢?

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
  }
}

这篇关于Django-rest框架,React JS,Axios-发布包含图像文件的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆