JavaScript: download file with fetch

In this post you will learn how to download a file in the background using client-side JavaScript and the fetch function to make HTTP requests.

We will see how to download a file as a blob using AJAX and then ask the user where to save it, suggesting a name.

The good thing about this is that we can send parameters to request the download of the file (for example, we can send a password over a POST request if the server requires it).

Creating HTTP request

As I said before, you can make any type of request, it doesn’t always have to be a GET. That depends on you, I have even tried with POST requests sending information, for example:

const response = await fetch("http://localhost:2106/auth/export_db", {
    method: "POST",
    credentials: 'include',
    body: JSON.stringify({
        password: "123",
        id: 1,
    }),
})

But the URL is up to you, as well as the server’s response. The response handling is the only thing that won’t change.

Note: remember that your code must be inside an async function to work.. If you are not using async, you can use fetch(...).then()

Download file with JavaScript

Once we have the response, we decode it as a blob and create a link that will have the content of the blob (don’t worry, it won’t be the request link, but a special one):

const fileContents = await response.blob();
const a = document.createElement("a");
const url = URL.createObjectURL(fileContents);
a.href = url;
a.download = "filename.extension";
a.click();
URL.revokeObjectURL(url);

In fact, the code is very similar to when we create and download a file with JavaScript, but now we are downloading it from a server.

With this, the download will be done in the background and then the user will be asked how they want to save the file.

The advantage of this is that we only use client-side JavaScript to download the file, and we can send parameters to the request, we are not forced to make an insecure GET request.

Note: if you want to see this in action you can watch my video where I export a database using exactly this code.


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

Leave a Comment

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