Categories
JavaScript Answers

How to download a file using window.fetch?

Spread the love

Sometimes, we want to download a file using window.fetch.

In this article, we’ll look at how to download a file using window.fetch.

How to download a file using window.fetch?

To download a file using window.fetch, we can call the response object’s blob method.

For instance, we write

const url = "http://example.com/file.doc";
const authHeader = "... ";

const options = {
  headers: {
    Authorization: authHeader,
  },
};
const res = await fetch(url, options);
const blob = await res.blob();
const file = window.URL.createObjectURL(blob);
window.location.assign(file);

to call fetch with the url with the file.

options has the headers for the request.

Then we call res.blob to get the content of the file as a blob.

Next, we call window.URL.createObjectURL with blob to create the file.

And then we call window.location.assign with file to download the file.

Conclusion

To download a file using window.fetch, we can call the response object’s blob method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *