Search code examples
reactjsaxiosmultipartform-data

Can I transfer a file in an object in formData format?


The forms provided by BackEnd are as follows

{
    dataInputDto: {

        itemIndex: string,
        addAuditData: {
                dataAnswer: string,
                fileList: Array<File>
        }

    }
}

I am using React and would like to send the data in multipart/formData format. But I've never transferred a file in that format, so please give me some advice!


Solution

  • Hope You're doing well.

    Let me share you a code snippet for the same so you may refer it and proceed further.

    The Submit function for the formData

    const onSubmit = async (data) => {
    let formdata = new FormData();
    formdata = { ...formdata, img: data.image[0] };
    console.log(formdata, formdata.img.name);
    
    let response = await axios.post(
      `${process.env.REACT_APP_BASEURL}/uploadImg`,
      formdata,
      { headers: { "Content-Type": "multipart/form-data" } }
    );
    

    The return function of the component is as follows to render the form

    <form onSubmit={handleSubmit(onSubmit)} encType="multipart/form-data">
    Id: <br />
    <input type="text" {...register("id")} defaultValue={id} readOnly />
    <br />
    Name: <br />
    <input type="text" {...register("name")} required />
     
    Image: <br />
    <input type="file" {...register("image")} required/>
    <br />
    <input type="submit" value="Submit" required/>
    </form>
    

    The Above Code Snippet is refering to image but you may also proceed same for transfering the file.

    Kindly Accept the Answer if it works for your query. Thanks & Regards.