- How to download a file in JavaScript
- You might also like.
- How to Download Any File In JavaScript
- What are Data URLs
- Dynamically Creating a Download Link
- How to Download Blobs in JavaScript
- In Conclusion
- Recommended
- How to 3D Flip Images With CSS
- How to Force Rerender Components in Svelte
- The Quick Way to Add Env Variables to Svelte using Vite
- Download File With Javascript Fetch (Simple Example)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- FETCH DOWNLOAD
- FETCH FILE DOWNLOAD
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- IT WORKS, BUT…
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
How to download a file in JavaScript
There are multiple ways available to download a file in JavaScript. You can either use the anchor’s download attribute or programmatically create an object URL in JavaScript.
The download attribute was added to the anchor element in HTML 5. It informs the browser to download the requested URL instead of navigating to it.
a href="file.pdf" download>Download PDFa>
You can also specify an optional value for the download attribute to be used as a file name once it is downloaded. If the value is not provided, the original filename is used.
a href="file.pdf" download="resume.pdf">Download PDFa>
As you can see above, the download attribute is the easiest way to download a file on the browser. You do not even need JavaScript for this since it is part of HTML DOM. However, the download attribute only works in modern browsers. Internet Explorer does not support it.
The idea is to programmatically create an anchor link, and then trigger the click event. This method is especially helpful for dynamically generated file URLs.
const download = (path, filename) => // Create a new link const anchor = document.createElement('a'); anchor.href = path; anchor.download = filename; // Append to the DOM document.body.appendChild(anchor); // Trigger `click` event anchor.click(); // Remove element from DOM document.body.removeChild(anchor); >; // Example download download('atta-resume.pdf', 'resume.pdf');
- creates an anchor element ( )
- set its target URL and download attribute value (if any)
- append it to the body
- trigger anchor’s click event to start download
- and finally remove the anchor tag from the body
Sometimes, you may want to save programmatically generated data as a file using JavaScript. That’s where blobs and object URLs are useful. A Blob object is a file-like object used to represent raw immutable data. Blob objects contain information about the type and size of data they store, making them very useful for storing dynamic contents in the browser. Let us say that you want to save the JSON response returned by a REST API as a file inside the browser:
fetch('https://reqres.in/api/users') .then(res => res.json()) .then(json => // TODO: Convert JSON object to blob >) .catch(err => console.error(err));
To create a blob object from the JSON data, you first need to convert it into a JSON string and then create an instance of the Blob by using its constructor:
// Convert JSON to string const data = JSON.stringify(json); // Create a Blob object const blob = new Blob([data], type: 'application/json' >);
To transform raw blob data into an object URL, you can use the URL.createObjectURL() method. This method is helpful to create an object URL that represents a blob or a file. Here is what it looks like creating an object URL:
const url = URL.createObjectURL(blob);
Now we have an object URL, we can simply call the download() method defined above to save the JSON response as a file:
By default, whenever an object URL is created, it remains in the DOM for the lifetime of the document. The browser will release all object URLs when the document is closed or reloaded. However, it is a good practice to release object URLs whenever they are no longer required to improve performance and minimize memory usage. To release URL objects, you can use the URL.revokeObjectURL() method:
fetch('https://reqres.in/api/users') .then(res => res.json()) .then(json => // Convert JSON to string const data = JSON.stringify(json); // Create a Blob object const blob = new Blob([data], type: 'application/json' >); // Create an object URL const url = URL.createObjectURL(blob); // Download file download(url, 'users.json'); // Release the object URL URL.revokeObjectURL(url); >) .catch(err => console.error(err));
You might also like.
How to Download Any File In JavaScript
In order to download any kind of file programmatically in JavaScript, we can use an invisible anchor with a download attribute. When the download attribute is set on an anchor, it will try to download the resource at the href attribute.
a href="/resources/report.pdf" download> a href="/resources/report.pdf" download="latest-reports.pdf">
By setting a value for the download attribute, we can specify a custom name for the downloaded file.
Of course, when we want to programmatically generate the file to be downloaded on the fly, we don’t have it available on the server, so there’s no URL to point the anchor to. To generate and download the file programmatically, we can use data URLs.
What are Data URLs
Data URLs are URLs prefixed with the data: scheme that allows us to inline small files into documents. We are going to use this approach to programmatically generate the resource that we want to download, in this example, a JSON file containing the necessary data. A data URL has the following format:
- The mediatype is a MIME type, such as image/jpeg or text/html . In our case, we will be using text/plain for plain text files. We are also going to need to set the character encoding to UTF-8 for the correct encoding format.
- There is an optional base64 string we can set in case we want to embed base64-encoded binary data. In our case, we can omit this value.
- Lastly, we have the actual data for the file. To convert the data into the correct URI string, we can use the built-in encodeURIComponent function.
This leaves us with the following for the data URL:
'data:text/plain;charset=utf-8,' + encodeURIComponent(data)
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Dynamically Creating a Download Link
In order to use our Data URL, we also need to dynamically create a link. For this, we can use document.createElement . This will create an anchor for us, on which we can set the href and download attributes accordingly, and then programmatically click on the link in order to trigger a download. With everything combined, we can use the following function to download a programmatically generated JSON file.
const download = (data, filename) => const data = JSON.stringify(data) const link = document.createElement('a') link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data)) link.setAttribute('download', filename || 'data.json') link.style.display = 'none' document.body.appendChild(link) link.click() document.body.removeChild(link) > // Later call it like so: download( name: 'John Doe', email: '[email protected]', phone: '+1 234 567' >) // Calling with a custom file name download( name: 'John Doe' >, 'user.json')
This function accepts a JavaScript object that will be converted into JSON. It can also optionally accept a filename as the second parameter. When the link is created, we can set the appropriate attributes on it using the setAttribute method. We also want to set its display property to none , in order to prevent the link from showing up anywhere on the page.
After all necessary attributes are present on the link, we can append the element to the document, using the appendChild method, and trigger a click on the link to initiate the download. After the download of the resource has been started, we can remove the link from the document using the removeChild method.
How to Download Blobs in JavaScript
The above method, however, is limited. It doesn’t work with non-text-based files, and while we could change the MIME type, it also doesn’t work with files hosted elsewhere. In order to come around this, introduce you to blobs.
Using blobs is a more generic approach to download binary files, or files that are not programmatically generated, but hosted elsewhere. For this, we need to use the fetch API in combination with the URL.createObjectURL to create the correct URL for the blob, then use this for the href . Based on this, our code changes to the following:
const download = async (url, filename) => const data = await fetch(url) const blob = await data.blob() const objectUrl = URL.createObjectURL(blob) const link = document.createElement('a') link.setAttribute('href', objectUrl) link.setAttribute('download', filename) link.style.display = 'none' document.body.appendChild(link) link.click() document.body.removeChild(link) > // Later call it with an URL and filename like so: download('https://unpkg.com/[email protected]/umd/react.production.min.js', 'react.js')
In the above example, we are using async/await to fetch the resource at the provided URL. We can then transform the returned result by using the blob method on it. Lastly, we then generate the proper blob URL using URL.createObjectURL which expects a blob to be passed for it.
// The returned value of a blob > Blob size: 10737, type: 'application/javascript' > // The returned value of a blob URL > 'blob:http://localhost:8080/b813048a-2074-4333-ac10-0b81b9c5ca17'
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
In Conclusion
In conclusion, we can either use a data URL to download dynamically generated files on the fly or use the fetch API with URL.createObjectURL to download blobs and files from other domains. Do you also need to read back files in JavaScript and monitor their progress? Check out our tutorial below.
How to Open Any File in Javascript with Progressbar Using an ASCII text art in your search bar Learn how you can open and read any file in JavaScript, and also show the progress of the reading with an ASCII text art in your search bar. Learn More
📚 More Webtips
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
- Unlimited access to hundreds of tutorials
- Access to exclusive interactive lessons
- Remove ads to learn without distractions
Recommended
How to 3D Flip Images With CSS
How to Force Rerender Components in Svelte
The Quick Way to Add Env Variables to Svelte using Vite
Get access to 300+ webtips 💌
Level up your skills and master the art of frontend development with bite-sized tutorials.
We don’t spam. Unsubscribe anytime.
Download File With Javascript Fetch (Simple Example)
Welcome to a tutorial and example of how to download a file using Javascript Fetch. Want to initiate a file download using Javascript Fetch? Yes, it is possible.
That should cover the basics, but if you need more concrete examples – Read on!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
FETCH DOWNLOAD
All right, let us now get into the example of downloading a file using Javascript fetch.
FETCH FILE DOWNLOAD
- Captain Obvious, the fetch() request itself.
- Return the server response as a blob object. Also, take note of the result != 200 check here. That’s right, fetch will consider it a success as long as there is a server response – Even when there are server errors such as 404 (not found) or 403 (unauthorized). So it is best to do a manual 200 (OK) check here.
- Create a download link to the blob object, and revoke it after the download is initiated.
- Handle errors. Optional, but highly recommended.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
IT WORKS, BUT…
I can understand the use of fetch to download a file that is protected or requires parameters to be generated dynamically.
// DATA TO BE ATTACHED var form = new FormData(); form.append("KEY", "VALUE"); // FETCH - MAYBE GENERATE A DYNAMIC REPORT fetch(url, < method:"post", body:form >) . SAME AS ABOVE .
But for you guys who just want to offer a download on a static file, just use the HTML anchor tag – . Yep, fetch download is cool, but don’t waste your time doing roundabout stuff.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!