iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📂

How to handle file downloads from the frontend

に公開2件

In modern web applications, there are many situations where a file download feature is required. For example, a "CSV download" feature that allows users to download CSV data generated by the backend as a file.

In this article, I will consider frontend implementation methods for downloading data obtained from an API[1] as a file.

Requirements

As mentioned earlier, the requirement we are considering here is to download data obtained from an API as a file. Specifically, we will consider the following requirements:

  • Call the API with a GET request and download its response as a file as is.
  • The download is triggered by some action on the frontend (such as a button click).

The approach may change depending on additional requirements, but for now, we will proceed with these assumptions.

The Best Method

First, I will introduce what I consider to be the best method.

That is, navigating to the API URL and leaving everything to the browser.

For example, suppose /api/csv is an API endpoint that returns CSV data.

On the frontend, you can trigger the CSV download with just this:

location.href = '/api/csv';

However, you may need to use the Content-Disposition header on the API side to ensure that the CSV data is downloaded as a file rather than displayed as a page.

In my opinion, if you can get by with this, it is the simplest and most desirable method.

There are many benefits to leaving file downloads to the browser. For example, pausing, resuming, canceling, and retrying on error can all be handled by the browser's download UI, allowing you to provide a feature-rich download UX without implementing anything on the frontend. Also, the download can continue even if the tab that triggered it is closed.

Q. But I want to display the download progress...

A. It will be displayed in the browser's UI.

Q. But I want to prepare my own progress display for the sake of UX...

A. Being able to use the browser UI that users are familiar with is the best UX.

So, if you're thinking about UX, it's best to leave it to the browser's file download feature.

However, since the article would be too thin with just this, I'll also consider cases where this method cannot be used for some reason. For example, when simple navigation is not possible due to authentication requirements.

A Common but Sub-optimal Method

When you cannot use the method of navigating to the API URL, a commonly used approach is to download data from the API using fetch (or XHR), hold it in a frontend buffer, and send it to the browser as a file once the download is complete.

Suppose the requirements state that you must display the download progress. In this case, you can take advantage of the fact that fetch downloads can be performed using streaming.

const response = await fetch('/api/csv');
// When the response is obtained, only the response headers have been received; the body is yet to come.

// Prepare a buffer to store the received data
const resultBuffer = new ArrayBuffer(0, { maxByteLength: 100 * 1024 ** 2 });
const result = new Uint8Array(resultBuffer)
let offset = 0;

// body is a ReadableStream object
const body = response.body;

// Process each received chunk
for await (const chunk of body) {
  resultBuffer.resize(offset + chunk.length);
  result.set(chunk, offset);
  offset += chunk.length;

  // Display progress
  console.log(`${offset} bytes received`);
}

// Once the download is complete, convert the buffer to a Blob,
// create a URL, and have the browser download it.
const blob = new Blob([resultBuffer.transferToFixedLength()], { type: response.headers.get('Content-Type') });
const url = URL.createObjectURL(blob);

const a = document.createElement('a');
a.download = 'data.csv';
a.href = url;
a.click();

In this example, we take advantage of the fact that the response.body of fetch is a ReadableStream object to display the download progress. A ReadableStream object can be processed as data is received using the for-await-of syntax. In this instance, we are using console.log to display the number of bytes received so far.

If the file size is known in advance, you can also display the percentage if you obtain it through some means.

Additionally, in this example, the ArrayBuffer (resultBuffer) used for writing is resized each time to secure storage space. This is a new feature of ES2024. Also, since a Blob cannot be created from a resizable ArrayBuffer, the transferToFixedLength method is used to convert it into a fixed-length ArrayBuffer. This is also a new feature of ES2024.

Many of you might have experience implementing file downloads using a method similar to the one above, though the details may differ.

However, despite having explained it, in my opinion, this is a sub-optimal method.

Specifically, the biggest disadvantage is the fact that the browser's download UI cannot be utilized. While this method does eventually download the file through the browser's download UI, it is sub-optimal in that "the actual download progresses within the tab, and the file appears in the download UI only after completion" (making it look like it was downloaded instantly from the perspective of the download UI).

Also, having to hold the data in memory during the download is not ideal. Since the entire data needs to be loaded into memory even for large files, there is a risk of high memory usage compared to native file downloads.

A Brute-Force Method Using Service Workers

In the method introduced above, we obtained a ReadableStream object as a result of fetch, but we had to convert it to a Blob in order for the browser to download it, which meant we couldn't take advantage of streaming and had to temporarily hold all the data in memory.

We want to improve this and connect the ReadableStream directly to the browser's download UI. That way, while we process the ReadableStream on the client, the browser's download UI should also work nicely.

Actually, Service Workers can be used to achieve this. However, this is a method that could be described as brute-force.

Specifically, the browser's download UI operates when downloading a file from a URL. And a Service Worker can hook into requests sent by the browser and return its own response. Using this, we can consider having a file downloaded from a URL handled by a Service Worker.

In other words, if you have a ReadableStream on hand, you somehow send it to the Service Worker. The Service Worker then echoes that data back from a download URL. By navigating the browser to that URL, the browser's download UI will trigger, and the download will begin.

With this mechanism, it is possible to connect data created on the client to the download UI for downloading.

I was thinking that preparing a sample for this would be a lot of effort even for an article, but I found a library that does exactly this. If you want to try what is described here, please take a look at the samples in this library.

https://github.com/jimmywarting/StreamSaver.js

Using the File System API

By the way, if you check the README of the library mentioned above, it mentions that nowadays, since the File System API (and its extension, the File System Access API) exists, this library will likely become unnecessary. So, let's look at the method using the File System API.

The specific implementation is as follows:

// Ask the user to select a save destination
const handle = await showSaveFilePicker({
  suggestedName: "data.csv",
  types: [
    {
      description: "CSV file",
      accept: {
        "text/csv": [".csv"],
      },
    },
  ],
});

const response = await fetch('/');
const body = response.body;
let offset = 0;

const writable = await handle.createWritable();

for await (const chunk of body) {
  // Write to the file
  await writable.write(chunk);
  
  offset += chunk.length;

  // Display progress
  console.log(`${offset} bytes received`);
}

// Close the file
await writable.close();

In short, you use a function called showSaveFilePicker from the File System Access API to have the user select a save destination.

Doing so provides a FileSystemFileHandle object, and by writing to it, you can download to the file the user selected.

While this method achieves the goal of saving a file to the user's machine while leveraging streaming, nothing is displayed in the browser's download UI. This is because, strictly speaking, it is not a "download."

Therefore, from the perspective of UX mentioned earlier, I ultimately cannot recommend it. In the File System Access API issues, there is a proposal to connect it with the download UI (the issue was opened by the author of the aforementioned library), but it does not seem to have gained much interest.

Summary

In this article, we have explored methods for downloading data obtained from an API as a file.

In my opinion, using the browser's download UI is still the simplest and most desirable method. However, this requires designing the API so that navigation to the download URL is possible. It is desirable to design this in coordination with the server-side.

If that is absolutely not possible, you either have to give up on the best UX or use a heavy-handed method like bringing in Service Workers (even though libraries exist).

Since file systems are an area where high security is naturally required, there are restrictions on free access. From the perspective of the evolution of Web standards, it seems best to leave it to the browser as much as possible.

脚注
  1. In this article, this refers to something implemented by the backend and exposed as an HTTP endpoint. Some schools of thought call this a Web API, but since it is understood even if I simply say "API", I will refer to it as "API" in this article. ↩︎

GitHubで編集を提案

Discussion

ナルミンチョナルミンチョ

https://vlngql-3000.csb.app/

他にも方法を考えてみました.

APIの呼び出しに, Authorization ヘッダーなどが不要で, Content-Disposition ヘッダーを付与できない事情があるなら, <a download href="/api/csv"></a> をクリックさせる方法がブラウザのダウンロードUIが利用できて良いですね

4
Katsuyuki KarasawaKatsuyuki Karasawa

Q. でもダウンロードの進捗状況を表示したい……
A. ブラウザのUIに表示されますよ。
Q. でもUXのために自前の進捗表示を用意したい……
A. ユーザーが使い慣れたブラウザのUIが使えるということが最高のUXですよ。

これ凄い真理ついてて笑っちゃいました。
ブラウザがいい感じにしてくれるならやっぱりそれに任せるのはベストだよなぁと感じますね。

3