简体   繁体   English

我正在使用 react.js 和 django 作为后端,我想使用 axios lib 将 react.js 表单中的图像上传到 django

[英]I'm using react.js and django for backend & I want to upload an image from react.js form to django using axios lib

This is my handle submit function I tried this way but there is something missing as I think这是我的句柄提交功能,我以这种方式尝试过,但我认为缺少一些东西

''''''' '''''''

handle = (event) => {
event.preventDefault();    
const name = event.target.name.value;
const barcode = event.target.barcode.value;
const category = event.target.category.value;
const description = event.target.description.value;
const image=new FormData();
image.append('image',event.target.image.value);

    axios.post('http://127.0.0.1:8000/admindashboard/products-create/', {
      name: name,
      Barcode: barcode,
      category: category,
      description: description,
      image

    }).then(result=>{console.log(result);
    });
  }

''' And this is my form ''' '''这是我的表格'''

 <Form onSubmit={(event) => this.handle(
          event
        )}
        class="ui form">

  <Form.Field>
        <input placeholder='product Name' name='name'/>
  </Form.Field>

  <Form.Field>
      <TextArea placeholder='Description' name='description' />
  </Form.Field>
  <Form.Field>
        <input placeholder='Barcode' name='barcode'/>
  </Form.Field>
  <Form.Field name='category' control='select'>
      {this.state.categories.map((cat)=>(<option name='category' value={cat.id}>{cat.name}
     </option>))}
  </Form.Field>

  <Form.Field>
  <input id="id_image"  type="file"  name="image"/>
  </Form.Field>

  <Button type='submit'>Submit</Button>
    </Form>

''''''''''''''''''''''''''' ''''''''''''''''''''''''''

Please help me find out what's wrong请帮我找出问题所在

You should do this :你应该做这个 :

event.preventDefault();

const data = new FormData() 
data.append('name', event.target.name.value)
data.append('barcode', event.target.barcode.value)
data.append('category', event.target.category.value)
data.append('description', event.target.description.value)
data.append('image',event.target.files[0]);

axios.post('http://127.0.0.1:8000/admindashboard/products-create/',data).then(result=>{console.log(result)});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM