close

How do I upload a file with the JS fetch API?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How do I upload a file with the JS fetch API ?

  1. How do I upload a file with the JS fetch API?

    do I upload a file with the JS fetch API The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
    data.append('fileData', { uri : pickerResponse.uri, type: pickerResponse.type, name: pickerResponse.fileName });
    Fetch seems to recognize that format and send the file where the uri is pointing.

  2. How do I upload a file with the JS fetch API ?

    do I upload a file with the JS fetch API The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
    data.append('fileData', { uri : pickerResponse.uri, type: pickerResponse.type, name: pickerResponse.fileName });
    Fetch seems to recognize that format and send the file where the uri is pointing.

Method 1


This is a basic example with comments. The upload function is what you are looking for:

// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');

// This will upload the file after having read it
const upload = (file) => {
  fetch('http://www.example.net', { // Your POST endpoint
    method: 'POST',
    headers: {
      // Content-Type may need to be completely **omitted**
      // or you may need something
      "Content-Type": "You will perhaps need to define a content-type here"
    },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);

// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);

Method 2

The problem for me was that I was using a response.blob() to populate the form data. Apparently you can’t do that at least with react native so I ended up using

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch seems to recognize that format and send the file where the uri is pointing.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment