Home > Back-end >  How can I send React post requet with file data to an API?
How can I send React post requet with file data to an API?

Time:02-24

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 React from 'react'
import { useState, getState } from "react";
import axios from "axios";
import { useDispatch, useSelector } from 'react-redux'

function VendorRegistration() {

      const [file, setFile] = useState(null);
     
    
      const UPLOAD_ENDPOINT =
        "http://127.0.0.1:8000/api/orders/vendor/register/";
    
      const handleSubmit = async e => {
        e.preventDefault();
        //if await is removed, console log will be called before the uploadFile() is executed completely.
        //since the await is added, this will pause here then console log will be called
        let res = await uploadFile(file);
        console.log(res.data);
      };

      const userLogin = useSelector(state => state.userLogin)
        const { userInfo } = userLogin
    
      const uploadFile = async file => {
        const formData = new FormData();
        formData.append("avatar", file);
      

       
        return await axios.post(UPLOAD_ENDPOINT, formData, {
          headers: {
            "content-type": "multipart/form-data",
            "Authorization" : `Bearer ${userInfo.token}`,
          }
        });
      };
    
      const handleOnChange = e => {
        console.log(e.target.files[0]);
        setFile(e.target.files[0]);
      };

      
    
      return (
        <form onSubmit={handleSubmit}>
          <h1>React File Upload</h1>
          <input type="file" onChange={handleOnChange} />
          <input type="name" />
          <button type="submit">Upload File</button>
        </form>
      );
    }
    
    
    


export default VendorRegistration

CodePudding user response:

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.

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 { userInfo } = useSelector((state) => state.userLogin);

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

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

export default VendorRegistration;
  • Related