Pure front-end implementation

Download static resources directly from the server

<a href="File link (confirmed URL)" download='Download file name'></a>
/ /! However, the Download file corresponding to the audio file and video file are invalid
// 'location.href', 'window.open()', etc
Copy the code

The front and back ends are realized

Implementation idea:

1. The front end sends data or parameters to the back end

2. Generate files based on the received data at the back end

3. The backend is then set in the response request header

The Content - disposition: attachment; filename="fliename.fileType"
Copy the code

4. After receiving the response file information, the front end processes the data and realizes the download.

Note: The common data types returned by the back end are Data stream and Base64, and the front-end handles them differently. The ultimate goal is to process them as BLOb objects for url.createObjecturl (BLOB) calls

The implementation code

Code:

// blobData File stream binary data returned by the background
// fileName specifies a custom fileName
// suffixName File name extension
// fileType Type of the file suffix
function exportFile(blobData, fileName, suffixName, fileType) {
    let blob = new Blob([blobData], { type: fileType })
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) // Create a download link
    downloadElement.href = href
    downloadElement.download =  fileName+ suffixName // Download the file name
    document.body.appendChild(downloadElement)
    downloadElement.click() // Click download
    document.body.removeChild(downloadElement) // Remove the element after downloading
}
/ / sample:
exportFile(blobData, 'Order Details'.'.xls'.'application/vnd.ms-excel');
Copy the code

Knowledge:

First, the object =new Blob( array, options );
The Blob() constructor returns a new Blob object. The content of a BLOB consists of a concatenation of values given in an array of parameters.
// array is an array made up of objects such as ArrayBuffer, ArrayBufferView, Blob, DOMString, etc., or a mixture of similar objectsCreateObjectURL = url.createObjecturl (object);// 1. It can get a memory URL for the current file. Then label a with that URL.
// 2. The object parameter is a File object, Blob object, or MediaSource object used to create the URL.Third, after research, we know that the back end returns a text stream, and then the front end needs to be converted into a file for download. Get the returned file stream, conversion, file name can be defined.Copy the code

Organize the configuration mapping tables for several common BLOBs

suffix The file type Type (type)
.xls Microsoft Excel application/vnd.ms-excel
.xlsx Microsoft Excel (OpenXML) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.csv CSV text/csv
.doc Microsoft Word application/msword