SoFunction
Updated on 2025-04-07

Summary of several common ways to implement file download in front-end

Front-end downloads in projects are generally divided into two situations:

  • The backend directly provides a file address, which can be downloaded by opening through a browser.
  • A request needs to be sent, the backend returns binary stream data, the frontend parses the stream data, and generates a URL to achieve download.

The essence of the front-end is a tag andBlobFile download, the difference between the two:

  • aTags: txt, png, jpg, gif and other files are not provided for direct download, and there are compatibility issues, especially IE.
  • blob: UtilizeBlobObjects can convert file streams intoBlobBinary object. This object is compatible and is suitable for situations where dynamically generating or processing of non-same-origin files is required. pass()Method converts the Blob object to a temporary URL download.

blob object

A Blob object represents an immutable, raw data-like file object. Its data can be read in text or binary format or converted intoReadableStreamto use for data operations. The Blob object is a newly added object in HTML5. Its function is to store binary data, such as pictures, videos, audio, etc.

property

  • size: read-only attribute, number of bytes in the blob.
  • type: read-only attribute, indicating the media type stored by the blob, pictures, videos, text files, etc.
    It is used as follows:
const blob = new Blob([], { type: '' });

()A static method creates aDOMString, which contains a Object given in the parameterURL. thisURLThe life cycle and the window that creates itdocumentBind. This newURLObject represents the specifiedFileObject orBlobObject.
When ourdocumentAfter being destroyed, thisURLIt will fail, so we need to destroy it at the right time.

Simply put, this method is used to create aurlIts function is to put ablobConvert an object into aurl,thisurlIt can be used to download files or preview files.

// Create a download linkconst url = (blob);
// Release the blob object(url);

Traditional a tag download

const a = ('a'); // Create a tag = 'display: none';
 = filename''; // Set the download file name = url; // Set the download address(a);
(); // Trigger the click event of a tag(a);

This method cannot solve the problem that the browser can recognize the file to be opened directly, but the new HTML5 attribute download attribute will solve this problem.

a tag + download attribute

whenURLWhen it is the same source (same domain name, same protocol, same port number), in this case, use the a tag to add the download attribute. The download attribute indicates that the browser should download instead of opening the file. At the same time, the value of the attribute is the file name when downloading;

<a href="path/to/" rel="external nofollow"  download=''>Click to download the picture</a>
const a = ('a'); // Create a tagconst e = ('MouseEvents'); // Create a mouse event object('click', false, false); // Initialize the event object = url; // Set the download address = filename || ''; // Set the download file name(e);

becausea tag download can only download the same sourceFile, if it isCross-domain files, including pictures, audio and video and other media files, all previews,Unable to download

fetch sends a request

  • Through native fetch requests, a tag is dynamically generated to achieve file download.
  • ()This method is the response object method of the Fetch API, which converts the file stream returned by the backend into a promise that returns a blob; blob (Binary Large Object) is a binary type object that records the original data information.
  • (blob)The return value of this method can be understood as a url pointing to the incoming parameter object through which the parameter can access the object passed in.
// Convert url to blob addressfetch(url)
    .then(res => ())
    .then(blob => {
        const a = ('a');
        // Convert link address character content into blob address         = (blob);
         = filename; // The name of the download file        (a);
        ();
        // After the download is completed, clear the occupied cache resources        ();
        (a);
    });
  • What should be noted in this method is that even if the same object is passed as a parameter, the URL object returned each time is different.
  • The url object is stored in memory and will only be cleared when the current document is uninstalled. Therefore, for better performance, it needs to be actively released through (blobUrl).

XMLHttpRequest

XMLHttpRequest (‌XHR for short)‌ is a Web API for creating communication between servers. ‌When downloading files, ‌ can be set byresponseTypeforblobto receive binary data. ‌This method is suitable for scenarios where file streams need to be obtained from the server and downloaded. Similar to Blob, ‌XHR can also be used to generate files dynamically and trigger downloads, but it provides more flexibility in handling asynchronous requests and data transfers. ‌

  • You can set the request header parameters.
  • The header parameters can be obtained by ('content-disposition').
let xhr = new XMLHttpRequest();
// GET request, downloadURL request path url, async (whether it is asynchronous)('GET', downloadURL, true);
// How to set the request header parameters, if there is no code, you can ignore this line of code("Token", 'Bearer ' + getStorage().token); // token
// Set the response type to blob = 'blob';
// Key parts = function () {
    //If the request is successful    if ( === 200) {
        // Download the file        const blob = new Blob();
        const href = (blob); // Create a download link        const a = ('a');
         = href;
         = fileName; // Download file name        (a);
        (); // Click to download        (a); // Download and remove elements        (href); // Release the blob object        
        // Can be passed ('content-disposition') header parameters, file name, etc.        // let headerParams = ('content-disposition')?.split(";") || [];
    }
};
// Send a request();
 = function () { 
    if ( === 4 &&  === 200) { 
        // Operation after success    } 
};

axios request method

axios({
    method: method ||'post',
    url,
    responseType: 'blob',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
        // Request parameters can be added here        token: 'tokenvalue'
    }
    data: (params)
}).then(res => {
    if (res) {
        const blob = new Blob(res);
        const url = (blob)
        const a = ('a')
         = 'none'
         = href;
         = fileName; // Download file name        (link)
        ()
        (link); // Download and remove elements        (url); // Release the blob object    } else {
        ('Download failed')
        return;
    }
})

Whether throughfetchXMLHttpRequestaxiosThe request and processing logic are obtained after the request is successful.response,thisresponseIt's what we want to download, by converting it intoblobObject, byCreate a downloadURL, download through the a tag.

Summarize

This is the article about several common ways to implement front-end file downloads. For more related front-end file downloading content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!