简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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