How to Download Files with JavaScript

Support for downloading files is a very common feature of web application. Over the past few years, I have developed this feature many times. In this article, we will learn how to download files…

image

Preface

Support for downloading files is a very common feature of web application. Over the past few years, I have developed this feature many times.

In this article, we will learn how to download files using JavaScript. We can achieve this in three ways:

  1. Use location.href
  2. Use the download attribute of the html <a> element
  3. Download the file as blob data using fetch and convert it to string via URL.createObjectURL()

1. Use location.href

When we need to open new page, always use the location.href . In some case, we can use it to download files.

When the browser detects an unsupported url response content-type of the url, it will download the file instead of opening it.

image

This demo shows that when we set the response content-type incorrectly, the browser will download it.

This way is very simple, but you need to ensure that the file cannot be opened in browser, you can try to open the file directly from local dist to test whether the browser supports it. It's not recommended to set unknown content-type only for downloading files.

The another way is to set Content-Disposition with attachment :

image

By setting Content-Disposition: attachment, the browser will download the file instead of opening it, and thee browser will automatically detect the file format accordingly to the content-type .

You can set the download filename in the server by adding filename to Content-Disposition:

image

If the server code can be modified, It's recommended to use the Content-Disposition to download the file.

2. Use the download attribute of the html <a> element

The download attribute in HTML5 is used to download files when users click on the hyperlink:

image

But if we want to download file from CDN, it won't work. The download only works for same-origin URLs, or the blob: and data: schemes.

In the next chapter, we will discuss how to download file from cross origin.

3. Use fetch API to download files

The download works for blob: scheme, but is restricted by same-origin URLs. If we can download the file and turn it into blob, we could continue use this functionality. Yeah, the fetch API supports request data from cross origin. So we can download file like the following way:

image

We can use the following function to download file:

function downloadFile(url, fileName) {
  fetch(url, { method: "get", mode: "no-cors", referrerPolicy: "no-referrer" })
    .then((res) => res.blob())
    .then((res) => {
      const aElement = document.createElement("a");
      aElement.setAttribute("download", fileName);
      const href = URL.createObjectURL(res);
      aElement.href = href;
      aElement.setAttribute("target", "_blank");
      aElement.click();
      URL.revokeObjectURL(href);
    });
}

You can test on Codepen.io:

Conclusion

In this article, we learn three ways to download files:

  1. Use location.href
  2. Use the download attribute of html <a> element
  3. Use fetch to download file

If the download file url is from the same origin, it is recommended to use localtion.href or download attribute, otherwise we can use the fetch API to download file and turn it into blob type data for <a> element.

I hope you found this article useful. You can learn more JavaScript at Certlibrary.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics