1

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?

4
  • Are you getting any error? Commented Apr 14, 2020 at 1:48
  • @Shohin - I'm getting 400 bad request Commented Apr 14, 2020 at 1:55
  • Does your HTML code have a form tag with an onSubmit. Ex: <form onSubmit={this.handleSubmit}> ReactJS Forms If not, then your handleSubmit function would not be called and there would not be any data in your post request. Commented Apr 14, 2020 at 2:26
  • @RaymondMutyaba - Yes i have. But its not working! Commented Apr 22, 2020 at 3:01

3 Answers 3

2

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)
    })
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting error in data: formdata as "Parsing error: The type cast expression is expected to be wrapped with parenthesis"
where is the error coming from exactly? could you post the stacktrace?
it's in axios.post line data:formData is showing as Parsing error: The type cast expression is expected to be wrapped with parenthesis
Hi, Do we need assign formData to data in axios post method? Coz if we assign then error is displaying like data is not defined
0

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.

1 Comment

I'm getting error in data: formdata as "Parsing error: The type cast expression is expected to be wrapped with parenthesis"
0
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.