7

I am trying to upload a file from frontend using reactjs. The backend is with Flask python. I am getting response code 400. What I am doing wrong?

frontend :

<input type="file" name="file" onChange={this.onChangeFile}/>
<button onClick={this.uploadFile}>
    Upload 
</Button>

uploadFile(e){
    e.preventDefault()
    let f = this.state.fileToBeSent
    let f_name = this.state.fileToBeSent.name
    console.log(f_name)

    let fileReader = new  FileReader()
    fileReader.readAsDataURL(f)
    fileReader.onload = (e) => {

      let toPost = {
        'file_name' : f_name,
        'file_data': e.target.result
      }
      console.log(toPost)
      return axios.post('/api/upload', toPost)
                  .then(res => console.log(res))
                  .catch(err => console.warn(err))
    }

  }

and on the backend :

@app.route('/api/upload', methods = ['POST'])
def upload_file():
    file = request.files['file']
    print(file)
    return "done"

1 Answer 1

11

You can use FormData to send your file instead.

Example

uploadFile(e) {
  e.preventDefault();
  let file = this.state.fileToBeSent;
  const formData = new FormData();

  formData.append("file", file);

  axios
    .post("/api/upload", formData)
    .then(res => console.log(res))
    .catch(err => console.warn(err));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, Thanks it worked. I dont understand though why that code with filereader didnt work
@TheTechGuy Great! You're welcome. I don't have that much experience with Flask, but I think the way you do it in your question sends the data as JSON, so Flask doesn't recognize it as a file. You can open up the network tab in your browser and compare the headers/data sent.

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.