illustrateRecently, I encountered a requirement to download files, but authentication is required. This means that you cannot use the download link returned by the background to download, because once someone gets the link, they can download it directly without any permission. Therefore, you need to change your thinking. After searching Baidu, you will learn about the blob object. This is what this article is about. Note: This article is only for recording learning tracks. If there is any infringement, please contact us to delete it. 1. Blob objectA Blob object represents an immutable, raw file-like object. Its data can be read in text or binary format, and can also be converted into a ReadableStream for data manipulation. 2. Front-endBlob download ideas:
Code: // Download export function download(query,newFileName) { return request({ url: '/file/download', method: 'get', responseType: 'blob', params: query }).then((res) => { /** * Blob download ideas * 1) Use ajax to initiate a request and specify the receiving type as blob (responseType: 'blob') * 2) Read the content-disposition in the header information returned by the request. The returned file name is in it (or you can customize the file name and skip this step) * 3) Use URL.createObjectURL to convert the requested blob data into a downloadable URL address* 4) Use the a tag to download* */ let blob = res.data // Get filename from the response headers, and the file name set by backend response.setHeader("Content-disposition", "attachment; filename=xxxx.docx"); // let patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*') // let contentDisposition = decodeURI(res.headers['content-disposition']) // let result = patt.exec(contentDisposition) // let fileName = result[1] //Convert the requested blob data into a downloadable URL address let url = URL.createObjectURL(blob) // Create a download tag <a> const aLink = document.createElement('a') aLink.href = url // 2. Use the custom file name directly to set the download file name aLink.setAttribute('download', newFileName ) document.body.appendChild(aLink) //Simulate click to download aLink.click() // Remove the download tag document.body.removeChild(aLink); }) } Calling this method //Download download(row) { // filePath: file path, for example: e:\upload\ // fileName: file name, for example: a.xlsx let form = { filePath: row.filePath, fileName: row.fileName, }; //Download, row.fileOriginalName is the original name of the file, which is only used to name the file when downloading. download(form, row.fileOriginalName); } // Since I am using Alibaba's OSS service, I only need to pass a file path back to the backend, query the OSS interface according to the file path to get the returned file stream, for example (BufferedInputStream), and set the return type in the response header 3. Backend
// response: response // filePath: file path, for example: e:\upload\ // fileName: file name, for example: a.xlsx public void download(HttpServletResponse response, String filePath, String fileName) { //File name to be downloaded response.reset(); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentType("application/octet-stream"); response.setCharacterEncoding("utf-8"); // Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // ossObject contains the name of the storage space where the file is located, the file name, file meta information, and an input stream. OSSObject ossObject = ossClient.getObject(bucketName, filePath + "/" + fileName); BufferedInputStream in = null; BufferedOutputStream out = null; byte[] buff = new byte[1024]; int length = 0; try { in = new BufferedInputStream(ossObject.getObjectContent()); out = new BufferedOutputStream(response.getOutputStream()); while ((length = in.read(buff)) != -1){ out.write(buff,0,length); } } catch (IOException e) { e.printStackTrace(); finally if(out != null){ try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (ossClient != null) { ossClient.shutdown(); } } } SummarizeThis article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM! You may also be interested in:
|
<<: HTML Editing Basics (A Must-Read for Newbies)
>>: Installation of mysql5.7 and implementation process of long-term free use of Navicate
This article shares the specific code of Vue2.0 t...
1. Install a virtual machine (physical machine) Y...
After MySQL is installed, you can verify whether ...
ENV: [root@centos7 ~]# uname -r 3.10.0-514.el7.x8...
Forgetting the password is a headache. What shoul...
Table of contents Overview Static type checking C...
The role of virtual DOM First of all, we need to ...
Preface Recently, I found a pitfall in upgrading ...
Table of contents Find and fix table conflicts Up...
Enter net start mysql in cmd and the prompt is: T...
There are two tables, and the records in table A ...
Some of you may have heard that the order of trav...
The author recently encountered a performance bot...
Table of contents Parent component communicates w...
A few days ago, I introduced to you a domestic xh...