Sandhya
Sandhya

Reputation: 541

Unable to upload file as a path to my form using reactjs

I'm new to Reactjs, my objective is to upload the file by giving the pathname (Ex: //downloads/users/image.jpg/) in my form. Though i was new to this platform, Couldn't bale to figure it out where i'm going wrong.

Here is the code of Form Submit:

handleSubmit = e => {
    e.preventDefault();
    const { firstName, LastName, phoneNumber, file} = this.state;
    const data = {
      firstName,
      lastName,
      phoneNumber,
      file
    };
axios.post(`/api/Form`, data, {
        headers: { 'Content-Type': 'application/json' }
      })
        .then(res => {
          console.log(res)
          console.log(res.data);
        })
        .catch((err) => {
          console.log(err)
        })

Can anyone help me in this query?

Upvotes: 1

Views: 1172

Answers (3)

Shohin
Shohin

Reputation: 558

Try to wrap your data and file inside FormData like so:

handleSubmit = e => {
    e.preventDefault();
    const { firstName, lastName, phoneNumber, file} = this.state;

    let formData = new FormData();
    formData.set("firstName", firstName);
    formData.set("lastName", lastName);
    formData.set("phoneNumber", phoneNumber);
    formData.append("file", file);

    axios.post('/api/Form', data: formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    .then(res => {
      console.log(res)
      console.log(res.data);
    }) 
    .catch((err) => {
      console.log(err)
    })
}

Upvotes: 2

Kiran Adhikari
Kiran Adhikari

Reputation: 105

import React,{useState} from 'react';
import axios from 'axios';

function App() {
 const [file, setFile] = useState('')
 async function fileUpload(files){
   try{
     const url = 'http://localhost:4545/upload';
     const formData = new FormData();
     formData.append('file',files);
     const config = {
       headers: {
           'content-type': 'multipart/form-data'
       }
   }
   await axios.post(url,formData,config)
   }
   catch(err){
     console.error(err)
   }
 }

 async function submitForm(e){
   e.preventDefault() 
   await fileUpload(file)
 }

 function onChange(e){
   e.preventDefault();
   setFile(e.target.files[0])
 }

 return (
 <div>
 <h1>Custom File Upload <span> With React</span></h1>
 <div class="custom-file-upload">
 <form onSubmit={submitForm}>
 <input type="file" onChange={onChange} />
 <button type="submit">Upload</button>
 </form>

</div>
 </div>
 );
}

export default App;

Upvotes: 0

JkAlombro
JkAlombro

Reputation: 1824

You are trying to upload a file object as a json which will result to bad request. You can create a formdata instead and append your file there. Then remove your content-type: application/json header.

handleSubmit = e => {
   e.preventDefault();
   const { firstName, LastName, phoneNumber, file} = this.state;

   //create formdata here
   let formdata = new FormData();
   formdata.append("firstName", firstName);
   formdata.append("lastName", lastName);
   formdata.append("phoneNumber", phoneNumber);
   formdata.append("file", file);

   axios.post(`/api/Form`, data: formdata)
   .then(res => {
     console.log(res)
     console.log(res.data);
   })
   .catch((err) => {
     console.log(err)
   })
}

I'm not really sure but I think there must also be some adjustments you should do with your api to handle formdata instead of json because there's no way to pass a file thru json.

Upvotes: 0

Related Questions