Search code examples
reactjsdjango

How can I send React post request with file data to an API?


Here I want to register user with image so I want to pass both image and name in my formdata. I am able to upload the file using some guideline (I am not good with react) but I am not able to pass the input name with my formdata. which procedure to follow?

import axios from "axios";
import React, { useState, useEffect } from 'react'
import { LinkContainer } from 'react-router-bootstrap'
import { Table, Button, Row, Col } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'

const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/vendor/register/";

function VendorRegistration() {
  const [file, setFile] = useState(null);
  const [name, setName] = useState("");
  const { userInfo } = useSelector((state) => state.userLogin);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append("avatar", file);
    formData.append("name", name);
   
    const resp = await axios.post(UPLOAD_ENDPOINT, formData, {
      headers: {
        "content-type": "multipart/form-data",
        Authorization: `Bearer ${userInfo.token}`,
      },
      
    });
    console.log(resp.status)
  };

  

  return (
    <form onSubmit={handleSubmit}>
      <h1>React File Upload</h1>
      <input type="file" onChange={(e) => setFile(e.target.files[0])} />
      <input type="text" onChange={(e) => setName(e.target.value)} value={name} />
      
      <button type="submit" disabled={!(file && name)}>
        Upload File
      </button>
      {resp.status == 200(
      <h1>ok</h1>
      )
}
    </form>

    
  );
  
}

export default VendorRegistration;

Solution

  • You'll just want to bind the other input to state as per usual, and then add that value to the form data.

    I added rudimentary validation that prevents clicking the submit button unless both fields are filled in, too.

    EDIT: I also added status responses, as per comments.

    import React from "react";
    import axios from "axios";
    
    const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/vendor/register/";
    
    function VendorRegistration() {
      const [file, setFile] = useState(null);
      const [name, setName] = useState("");
      const [status, setStatus] = useState("");
      const { userInfo } = useSelector((state) => state.userLogin);
    
      const handleSubmit = async (event) => {
        setStatus(""); // Reset status
        event.preventDefault();
        const formData = new FormData();
        formData.append("avatar", file);
        formData.append("name", name);
        const resp = await axios.post(UPLOAD_ENDPOINT, formData, {
          headers: {
            "content-type": "multipart/form-data",
            Authorization: `Bearer ${userInfo.token}`,
          },
        });
        setStatus(resp.status === 200 ? "Thank you!" : "Error.");
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <h1>React File Upload</h1>
          <input type="file" onChange={(e) => setFile(e.target.files[0])} />
          <input type="text" onChange={(e) => setName(e.target.value)} value={name} />
          <button type="submit" disabled={!(file && name)}>
            Upload File
          </button>
          {status ? <h1>{status}</h1> : null}
        </form>
      );
    }
    
    export default VendorRegistration;