preface

Users often need to click a button or link to complete the file download, so how does front-end download work?

Think about it: when the user clicks, it will inevitably send a request to the back end, and the back end returns the data to the front end, which completes the download through a series of processes. So it’s still essentially a matter of processing the data. For the front end, we need to consider:

  • What does the back end return?

  • How does the front end handle the data?

When the back end returns the link

When the back end returns a direct access to the download link (you can visit the link in the browser address bar to see the effect)

How to deal with the front end: the download attribute of a tag

Note: Links must be homologous and cross-domain is not supported

 < a href = "Homologous link" download = "File name > Click download Copy the code

When the back end returns data

When the back end returns data, such as JSON, it needs to be written to a file and downloaded using Blob objects. The following uses json data returned as an example:

const onClick = () = > {                   // Click the event
    getData(urlParam).then((res) = > {    // Return data
            const content = JSONStringify (res);// JSON data is converted to a string
            const blob = new Blob([content], { type: 'application/json,charset=utf-8' }) // New Blob object, type optional
            const url = window.URL.createObjectURL(blob);   // New blobUrl object
            const link = document.createElement('a');       // Generate links
            link.href = url;
            link.setAttribute('download'.'File name');
            document.body.appendChild(link); 
            link.click();                      // Trigger the link click event to complete the automatic download
            document.body.removeChild(link);   // Remove the link after click})}Copy the code

The summary is:

Interface returns data -> String -> Create BLOB object with string -> Create download link URL with BLOB object -> A tag

For details on what bloBs and createObjectURL are in code and how to use them, please read the official documentation:

Blbb:developer.mozilla.org/zh-CN/docs/… CreateObjectURL:developer.mozilla.org/zh-CN/docs/…