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.

To download a file using Javascript fetch, return the result as a blob, and create a download link to the blob object.

  • fetch("URL")
  • .then((res) => { return res.blob(); })
  • .then((data) => {
  •   var a = document.createElement("a");
  •   a.href = window.URL.createObjectURL(data);
  •   a.download = "FILENAME";
  •   a.click();
  • });

That should cover the basics, but if you need more concrete examples – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Fetch Download Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

FETCH DOWNLOAD

All right, let us now get into the example of downloading a file using Javascript fetch.

 

FETCH FILE DOWNLOAD

fetch-download.html
<script>
function fetchDown (url, saveas) {
  // (A) FETCH FILE
  fetch(url)
 
  // (B) RETURN AS BLOB
  .then((result) => {
    if (result.status != 200) { throw new Error("Bad server response"); }
    return result.blob();
  })
 
  // (C) BLOB DATA
  .then((data) => {
    // (C1) FILE DATA IS "READY FOR USE"
    console.log(data);
 
    // (C2) TO "FORCE DOWNLOAD"
    var url = window.URL.createObjectURL(data),
    anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = saveas;
    anchor.click();
 
    // (C3) CLEAN UP
    window.URL.revokeObjectURL(url);
    document.removeChild(anchor);
  })
 
  // (D) HANDLE ERRORS - OPTIONAL
  .catch((error) => { console.log(error); });
}
</script>
 
<input type="button" value="Download"
       onclick="fetchDown('orange.jpg', 'demo.jpg')"/>

This is the “full version” of the introduction snippet. Should be self-explanatory, but a quick walkthrough:

  1. Captain Obvious, the fetch() request itself.
  2. 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.
  3. Create a download link to the blob object, revoke it after the download is initiated.
  4. Handle errors. Optional, but highly recommended.

 

 

USEFUL 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 you need to send some parameters to generate a dynamic file… But for you guys who just want to offer a download on a static file, just the HTML anchor tag – <a href="URL" download>. Yep, fetch download is cool, but don’t waste your time doing roundabout stuff.

 

LINKS & REFERENCES

 

 

INFOGRAPHIC CHEAT SHEET

Javascript Fetch Download File (click to enlarge)

 

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!

Leave a Comment

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