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

Grid systems in web design

Formation of the grid system In 1692, the newly c...

Java+Tomcat environment deployment and installation process diagram

Next, I will install Java+Tomcat on Centos7. Ther...

Detailed explanation of destructuring assignment syntax in Javascript

Preface The "destructuring assignment syntax...

Initial settings after installing Ubuntu 16 in the development environment

The office needs Ubuntu system as the Linux devel...

Talk about implicit conversion in MySQL

In the course of work, you will encounter many ca...

How to use sed command to efficiently delete specific lines of a file

Preface Normally, if we want to delete certain li...

Detailed explanation of formatting numbers in MySQL

Recently, due to work needs, I need to format num...

React hooks introductory tutorial

State Hooks Examples: import { useState } from &#...

Detailed summary of web form submission methods

Let's first look at several ways to submit a ...

A practical record of an accident caused by MySQL startup

Table of contents background How to determine whe...