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).
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()
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.
In the last months I have been working on a ticket designer to print on…
In this post you will learn how to use the Origin Private File System with…
In this post I will show you how to use SQLite3 directly in the web…
In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…
When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…
In this post I will show you how to print spanish text, text with accents…
Esta web usa cookies.