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
Requirement: The page needs to display an image, ...
It is essentially a common js object used to desc...
Recently, I have been studying the MySQL database...
I won’t go into details about the theory of UDP. ...
1. Execute the select statement first to generate...
Table of contents Preface Style Function Descript...
html ¶ <html></html> html:xml ¶ <h...
Today I saw a friend asking a question in the Q&a...
Table of contents 1. Preprocessing 2. Pretreatmen...
This article describes how to configure time sync...
Physically speaking, an InnoDB table consists of ...
Table of contents 1. Merge interface 1.1 Non-func...
If a form field in a form is set to disabled, the ...
This article shares the specific code of jQuery...
A brief description of environment variable confi...