“This is the 17th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”.
File download, in the past, the back-end program generated files on the server side, and then the front end downloaded data from the server side by opening the link, and the file to be downloaded will have a temporary file or permanent file on the server. With the development of browsers and the popularity of advanced browsers, file download can obtain the corresponding file stream through the interface, and then generate the corresponding download file and link address in the front end. In this way, there are no temporary files or permanent files on the server, but the file data stream is stored in the database.
This article shows you how to generate and download files using native JavaScript.
Generate the file
For working with files, browsers have the high-level object File API, which is now widely supported by browser vendors. The File interface is based on Blob, inherits Blob functionality and extends it to support files on the user’s system. As follows:
Const file = new file (["DevPoint, devtech "], "info.md", {type: "text/plain",});Copy the code
The parameters are described as follows:
The data array
: the first argument, which can beBlob
,ArrayBuffer
Or a string.The file name
The second parameter is the file name, including the file suffix.Configuration file
: This is an optional argument, passing the actual type of the file.
To generate a file that contains data of type TEXT /plain (text, HTML, CSV, etc.), generating more abstract file types requires the use of blobs or buffers.
CSV or EXCEL:
const file = new File([filedata], "info.xlsx", {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
Copy the code
Blob
The ArrayBuffer is part of the ECMA standard, and it’s also part of JavaScript. Generate files in the browser, in addition to the high-level object File API described above, and bloBs.
Blob (Binary Large Object) represents a Large Object of Binary type. In a database management system, the storage of binary data as a single collection of individuals. Blobs are usually video, sound, or multimedia files. Blob objects in JavaScript represent immutable file-like raw data.
A Blob consists of an optional string type (usually a MIME type) and blobParts: a sequence of other Blob objects, strings, and bufferSources.
The constructor syntax is:
new Blob(blobParts, options);
Copy the code
blobParts
Is:Blob/BufferSource/String
The value of the arrayoptions
: Optional objecttype
: Blob type, usually MIME type, for exampletext/plain
endings
: The default value istransparent
To specify the inclusion line terminator\n
How the string is written. It is one of two values:native
, indicating that the end-of-line character is changed to a newline suitable for the host operating system file system, ortransparent
Delegates will remainblob
The end character saved in.
The download file
To check that the creation file is valid, access it and download it.
This is done by generating a link containing a reference to the file. Then, have the JavaScript start time click to click the link so the file can be downloaded.
To receive the file URL, you need to use the url.createObjecturl () method to accept the file object as an argument. Then, specify the default file name to save by setting the download property of the link.
Finally, mount the link in the DOM, click it, and remove it from the DOM. Here is the complete code:
Const file = new file (["DevPoint, devtech "], "info.md", {type: "text/plain",}); function download(downfile) { const tmpLink = document.createElement("a"); const objectUrl = URL.createObjectURL(downfile); tmpLink.href = objectUrl; tmpLink.download = downfile.name; document.body.appendChild(tmpLink); tmpLink.click(); document.body.removeChild(tmpLink); URL.revokeObjectURL(objectUrl); } download(file);Copy the code
If you are accessing the file stream via an interface and generating a download file, you can refer to the following Vue code snippet:
apiClient .get(apiFileUrl, { responseType: "arraybuffer", }) .then((response) => { const { headers, data } = response; const fileinfo = { blobData: data, fileName: ((strDispostion) => { if (strDispostion) { if ( strDispostion ! == "" && strDispostion.split("filename=").length > 1 ) { return decodeURIComponent( strDispostion.split("filename=")[1] ); } else { return "tempname"; } } })(headers["content-disposition"]), }; const tmpLink = document.createElement("a"); const { blobData, fileName } = fileinfo; const blob = new Blob([blobData], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); const objectUrl = URL.createObjectURL(blob); tmpLink.href = objectUrl; tmpLink.download = fileName; document.body.appendChild(tmpLink); // You don't need this line of code if you don't need to display the download link. URL.revokeObjectURL(objectUrl); });Copy the code