javascript Blob object to achieve file download

javascript Blob object to achieve file download

illustrate

Recently, 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 object

A 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-end

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 skip this step if you customize the file name)
3) Use URL.createObjectURL to convert the requested blob data into a downloadable URL address
4) Download using the a tag

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

The backend uses Alibaba's OSS service here to directly get the file stream (new BufferedInputStream(ossObject.getObjectContent())). If it is not OSS, you only need to read the file (File) on the corresponding server, convert it to BufferedInputStream, and then directly apply the following code (that is, set BufferedOutputStream through response.getOutputStream())

	// 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();
            }
        }
    }

Summarize

This 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:
  • JavaScript File Multipart Upload
  • javascript gets the full path of the form file
  • Detailed explanation of the principle and usage of JavaScript Blob object
  • Introduction and use of Blob objects in js
  • Solution to the video download problem of js blob type URL
  • Javascript File and Blob Detailed Explanation

<<:  HTML Editing Basics (A Must-Read for Newbies)

>>:  Installation of mysql5.7 and implementation process of long-term free use of Navicate

Recommend

MySQL Community Server compressed package installation and configuration method

Today, because I wanted to install MySQL, I went ...

Detailed tutorial on how to install mysql8.0 using Linux yum command

1. Do a good job of cleaning before installation ...

Detailed explanation of where the images pulled by docker are stored

The commands pulled by docker are stored in the /...

Implementation of local migration of docker images

I've been learning Docker recently, and I oft...

How does Vue track data changes?

Table of contents background example Misconceptio...

Vue implements the full selection function

This article example shares the specific code of ...

Detailed steps to install Mysql5.7.19 using yum on Centos7

There is no mysql by default in the yum source of...

MySql 8.0.16-win64 Installation Tutorial

1. Unzip the downloaded file as shown below . 2. ...

vue3+ts+EsLint+Prettier standard code implementation

Table of contents use Use of EsLint Add a profile...

CSS optimization skills self-practice experience

1. Use css sprites. The advantage is that the smal...

Specific use of Docker anonymous mount and named mount

Table of contents Data volume Anonymous and named...