uploading file with fetch 1

uploading file with fetch

// 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);

Here is what the above code is Doing:
1. We select the input type file element and store it in a variable.
2. We define a function that will upload the file to the server.
3. We define a function that will be executed when a file is selected.
4. We add a listener on the input element that will trigger the function defined in step 3.

The upload function is using the fetch API to send the file to the server.

The fetch API is a promise-based mechanism, and calling fetch() is equivalent to defining our own promise using new Promise().

The fetch() function will return a promise with our JSON data.

The first then() function will execute the JSON response so that the second then() function will have JSON object in its response.

The second then() function will get the JSON object and process it accordingly.

The catch() function will execute in case of error.

The fetch() function takes one mandatory argument, the path to the resource we want to fetch.

It returns a promise that resolves to the Response to that request, whether it is successful or not.

The Response object contains the response to the request.

The response is a JavaScript object created by parsing the contents of received data as JSON.

The response object has these properties:

ok – (boolean) True if the response is successful (status in the range 200-299) or false otherwise.
status – (number) The HTTP status code of the response (e.g., 200 for a success).
statusText – (string) The HTTP status message (e.g., OK for 200).
url – (string) The final URL obtained after any redirects.
type – (string) The type of response. It can be one of basic, cors, default, error, or opaque.
useFinalURL – (boolean) True if the URL of the response can be used in the context of the current origin.

The response object also has these methods:

clone() – Creates a clone of the response.
error() – Creates a new response with an error response.
redirect() – Creates a new response with a different URL.

The response object has these properties:

body – (ReadableStream) A ReadableStream of the body contents.
bodyUsed – (boolean) True if the body has already been read, otherwise false.
headers – (Headers) The Headers object associated with the response.
ok – (boolean) True if the response is successful (status in the range 200-299) or false otherwise.
redirected – (boolean) True if the response is a redirected response, otherwise false.
status – (number) The HTTP status code of the response (e.g., 200 for a success).
statusText – (string) The HTTP status message (e.g., OK for 200).
type – (string) The type of response. It can be one of basic, cors, default, error, or opaque.
url – (string) The final URL obtained after any redirects.

The response object also has these methods:

arrayBuffer() – Returns a promise that resolves with an ArrayBuffer.
blob() – Returns a promise that resolves with a Blob.
formData() – Returns a promise that resolves with a FormData object.
json() – Returns a promise that resolves with a JSON object.
text() – Returns a promise that resolves with a USVString (text).

The response object has these properties:

body – (ReadableStream) A ReadableStream of the body contents.
bodyUsed – (boolean) True if the body has already been read, otherwise false.
headers – (Headers) The

Similar Posts