0

I have this handler to make api calls to an endpoint:

handleFileChange(e) {
  e.preventDefault();
  fetch(apiAddress)
    .then((res) => {
      return res.json()
    }).then( (res)  => {
      this.props.onFileChange(JSON.stringify(res));
  });
}

And i would like send a file as part of the requests like this:

render(){
  getScene();
  return (
    <form>
     <input type='file' name='uploaded_file' />
     <button onClick={this.handleFileChange}>Upload</button>
   </form>
  )
}

How can it do that with the file added in that form?

1 Answer 1

1

This is just as simple as POSTing the File to the API:

handleFileChange(e) {
  e.preventDefault();
  let fileInput = document.getElementsByName("uploaded_file")[0];
  fetch('/yourEndpoint', {
    method: 'POST'
    body: fileInput.files[0] // This is your file object
    headers: {
      "Content-Type": fileInput.files[0].type // this is the MIME type of the data *
    },
  }).then(
    response => response.json()
  ).then( res => {
    this.props.onFileChange(JSON.stringify(res))
  });
}

* note, however, that this is generated from the file extension, so it can easily be spoofed

Sign up to request clarification or add additional context in comments.

7 Comments

I don't need to specify anything else? Like content type or something?
Your browser should handle this for you.
Is not doing it. And acording to the network console the conten type is text/plain and I'm geting a 404. The api is also mine, built with Spark, so maybe the problem is something else. But I know is working by using a simple form in plain html.
Yes, using react im getting a 404. But using a basic form it works.
Is the server crashing when you post to it this way? Because, a 404 is for when the requested resource can't be located, which shouldn't happen, if the url is correct
|

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.