[File download operation 1] Commonly used by the front end to cooperate with the back end to download files ==> download by url ==> download by blob

When I stop being clinging to me and look at myself from a higher perspective, I can truly see my truer self.

                                                                      ---I am waiting for you in the future

Current project: network security information system security operation and maintenance management platform

This chapter mainly involves: work order management, resource configuration template download and operation audit


Table of contents

1. Download files according to url

1. Functional design

2. Interface return value

3. Front-end implementation

(1) Method 1: window.open

 (2) Method 2: Convert a tag url to blob download

2. Download files according to the file stream

1. Functional design

2. Interface return value

(1) Front-end code logic framework

 (2) Front-end interface call

(3) Backend returns data

​3. Front-end implementation

(1) Add responseType: 'blob' after the interface


1. Download files according to url

1. Functional design

Click the template link to download the file. The file name of the downloaded file corresponds to the template name.

2. Interface return value

// 资源管理页面-导入-下载模板
export function getTemplate(type) {
  return request({
    url: "/api/resource/allocation/resource/management/import/template/" + type,
    method: "get",
  });
}

3. Front-end implementation

(1) Method 1: window.open

使用  window.open(res.data.url, "_blank");

Syntax: window.open([URL], [window name], [parameter string])

If wendow.open puts a file in it, it will definitely download the file

// 导入模块-下载模板
downloadTemplate(type) {
  getTemplate(type).then((res) => {
     console.log(res.data, "================");
     window.open(res.data.url, "_blank");
  });
},

Achievement effect: download the file at the bottom of the page, but! ! ! The file name cannot be modified! ! !

 (2) Method 2: Convert a tag url to blob download

// window.open(res.data.url, "_blank");
// 方法2
const url = res.data.url;
const blob = new Blob([url], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-UTF-8",});
const blobUrl = URL.createObjectURL(blob);
const downloadElement = document.createElement("a");
console.log(downloadElement);
downloadElement.style.display = "none";
downloadElement.target = "_blank";
downloadElement.href = blobUrl;
downloadElement.download = "模板.xlsx";
document.body.appendChild(downloadElement);
downloadElement.click();
URL.revokeObjectURL(url); // 释放内存

 Effect: You can see that this method can modify the file name of the file, but after the file is opened, the content becomes url

 This method of url becoming blob is wrong

The correct way is as follows:

// 方法2
        // 将url转成blob地址,
        const url = res.data.url;
        const name =
          type == 1
            ? "服务器模板.xlsx"
            : type == 2
            ? "数据组件模板.xlsx"
            : "网络和安全设备模板.xlsx";
        const a = document.createElement("a");
        fetch(url)
          .then((res) => res.blob())
          .then((blob) => {
            // 将链接地址字符内容转变成blob地址
            a.href = URL.createObjectURL(blob);
            console.log(a.href);
            a.download = name; // 下载文件的名字
            // a.download = url.split('/')[url.split('/').length -1] //  // 下载文件的名字
            document.body.appendChild(a);
            a.click();
          });
      });

2. Download files according to the file stream

1. Functional design

 The page realizes single file download and file batch download to generate compressed package 

2. Interface return value

(1) Front-end code logic framework

 handleDownload(row) {
      const ids = row.id != undefined ? [row.id] : this.ids;
      if (ids.length === 0) {
        this.$message.warning("请勾选数据");
      } else if (ids.length === 1) {
        downloadOneData({ ids: ids }).then((res) => {
          // window.open(res.data.url, "_blank");
          // 下载
        });
      } else {
        downloadBatchData({ ids: ids }).then((res) => {
          // 下载
        });
      }
    },

 (2) Front-end interface call

export function downloadOneData(ids) {
    return request({
        url: '/api/work/order/download',
        method: 'post',
        data: ids
    })
}
export function downloadBatchData(ids) {
    return request({
        url: '/api/work/order/download',
        method: 'post',
        data: ids,
        responseType: 'blob'
    })
}

(3) Backend returns data

When a single file is downloaded, the returned data is url

 When multiple files are downloaded, the returned data is a file stream

 3. Front-end implementation

The idea of ​​downloading a single file is the same as the first step above

downloadOneData({ ids: ids }).then((res) => {
          // window.open(res.data.url, "_blank");
          const url = res.data.url;
          const name = res.data.name + "." + res.data.suffix;
          const a = document.createElement("a");
          fetch(url)
            .then((res) => res.blob())
            .then((blob) => {
              // 将链接地址字符内容转变成blob地址
              a.href = URL.createObjectURL(blob);
              console.log(a.href);
              a.download = name; // 下载文件的名字
              document.body.appendChild(a);
              a.click();
            });
        });

(1) Add responseType: 'blob' after the interface

When downloading multiple files

downloadBatchData({ ids: ids }).then((res) => {
          var blob = new Blob([res], {
            type: "application/zip;charset-UTF-8",
          });
          const blobUrl = URL.createObjectURL(blob);
          const downloadElement = document.createElement("a");
          downloadElement.style.display = "none";
          downloadElement.href = blobUrl;
          downloadElement.download = "工单申请表.zip";
          downloadElement.click();
          URL.revokeObjectURL(blobUrl); // 释放内存
        });

Reference link: common method and principle analysis of front-end file download_fisher-CSDN blog_front-end file download

The front end downloads the file successfully, but it cannot be opened - Programmer Sought

Problems encountered and records:

1. When loading a single file and modifying the file name, the window.open method is not used

2. The file is downloaded successfully but it shows that the file is damaged ==> add type after the interface

3. The file is downloaded successfully, but the content of the file becomes url ==> use the correct method to convert url to blob

Guess you like

Origin blog.csdn.net/Sabrina_cc/article/details/123092888