DEV Community

AMRIT SHAHI
AMRIT SHAHI

Posted on

Unable to sent image attachement to django backend. Help appricated

`import React, { useState } from "react";
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

function CompanyForm() {
  const [name, setName] = useState("");
  const [title, setTitle] = useState("");
  const [price, setPrice] = useState("");
  const [upload, setUpload] = useState(null);

  const navigate = useNavigate();

  const AddInfo = async () => {
    let formField = new FormData()

    formField.append('name', name)
    formField.append('title', title)
    formField.append('price', price)
    formField.append('upload', upload)

    if (upload !== null) {
      formField.append('upload', upload)
    }


    const AddInfo = () => {
      const formField = new FormData()
      formField.append('name', name)
      formField.append('title', title)
      formField.append('price', price)
      formField.append('upload', upload)

    }

    await axios({
      method: 'POST',
      url: 'http://localhost:8000/',
      data: formField,

      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },

    }).then((res) => {
      console.log(res.data)
      navigate('/')
    })

  }


  return (
    <form>
      <div className="mb-3">

        <label for="Name" className="form-label">Name</label>
        <input type="text" className="form-control" name="name" value={name} onChange={(e) => setName(e.target.value)} />
      </div>

      <div className="mb-3">
        <label for="title" className="form-label">Title</label>
        <input type="text" className="form-control" name="title" value={title} onChange={(e) => setTitle(e.target.value)} />
      </div>
      <div className="mb-3">
        <label for="price" className="form-label">Price</label>
        <input type="number" className="form-control" name="price" value={price} onChange={(e) => setPrice(e.target.value)} />
      </div>
      <div class="mb-3">
        <label for="upload" class="form-label">Upload</label>

        <input class="form-control" type="file" name="upload" onChange={(e) => setUpload(e.target.files[0])} />
      </div>

      <button type="submit" className="btn btn-primary" onClick={AddInfo}>Submit</button>
    </form>
  )
}

export default CompanyForm;`
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)