Several common methods distal download / export file comparison

Foreword

In the front page, this is a very common requirement, so to sum up, improve work efficiency to facilitate future

1.window.open or window.location.href

let url = '/api/dhr/test_reports/download';
window.open(`${url}?session=${session}&staff_id=${query.staff_id}`, "_blank")

Pros: Easy Direct

Disadvantages: 1. have problems URL length restriction

           2. not know the progress of the download

          3. The browser can directly browse the file type is not available for download, such as txt, png, jpg, gif, etc.

          4. You can not add header information, it can not be authenticated

2.a label download

<a target="_blank" download=”aaa”
    href={`/api/dhr/projects_staffs_perform/download_template?    
    session=${token}&project_id=${projectId}`}>
<p>下载标准 Excel 模板</p></a>

Advantages: can solve not directly download the browser can browse files

Download the file was known address: Disadvantages

          Under cross-domain can not download the browser can browse files

          Compatibility, especially IE

          Can not be authenticated

3. Use the blob

The advantage with the method is that a label, which in addition to the path using the known address of the file for download, but also can obtain the file stream api download request by sending ajax

You can use the blob Blob stream into binary object files, access Blob url on safari browser is flawed, as generated by URL.createObjectURL link

Ideas for download is very simple, the binary data acquired retransmission request, into the Blob object generated using URL.createObjectURL URL address assignment for download on the binding properties download a href attribute tag

This method does not attribute a lack download tag data types because the event is set to send a request for the return of the Blob, the blob is a so target.response, print it out will see two properties size and type, although the type attribute specifies the file type it, but in order to secure, or to specify the file extension on the download properties

//通过ajax获取二进制数据
export const exportPageToPdf = (query) => {
   return axios('/api/export-page-pdf, {
   params: {
    session: Cookies.get('dhr_b_token'),
   },
   responseType: 'arraybuffer',
  })
  .then((res) => {
   return new Blob([res.data]);
  })
  .then((data) => {
   return window.URL.createObjectURL(data);
 });
}
调用
exportPageXls({
    session: Cookies.get('dhr_b_token'),
})
.then((url) => {
    this.download(url,'盘点数据', 'xlsx');
})
.catch((err) => {
    Toast.info('文件下载失败。');
});
创建a标签给href属性赋值
download = (blobUrl, filename, suffix) => {
    let a = document.createElement('a');
    a.style.display = 'none';
    a.download = `${filename}_建模报告.${suffix}`;
    document.body.appendChild(a);
    a.href = blobUrl;
    a.click();
    document.body.removeChild(a);
};

Advantages: can solve not directly download the browser can browse files

          You can know the download progress

          You can set header

Cons: compatibility issues. IE10 The following is unavailable, safari browser can look at usage

4. use base64

Blob with similar basic ideas about the same, the only difference is that the above is the use of Blob Blob URL and generate the object here is to generate (url form after base64 encoded) Data URL

ajax获取
export const exportPageXls = (query) => {
    let url = '/api/dhr/talent_excel/download';
    return axios(url, {
        params: query,
        responseType: 'arraybuffer',
    })
    .then((res) => {
        let blob=new Blob([res.data]);//{size:11111,type:’’}
        let fileReader = new FileReader()
        fileReader.readAsDataURL(blob) //将blob变成base64
        return fileReader
})
}
调用
exportPageXls({
    session: Cookies.get('dhr_b_token'),
})
.then((fileReader) => {
    this.download(fileReader,  '盘点数据', 'xlsx');
})
.catch((err) => {
    Toast.info('文件下载失败。');
});
创建a标签
download = (fileReader, filename, suffix) => {
    fileReader.οnlοad=function(){
    let a = document.createElement('a');
    a.style.display = 'none';
    a.href = this.result; //base64
    a.download = `${filename}.${suffix}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
};

Pros: Like blob

Disadvantages: compatibility, IE10 unavailable or less

 

These are commonly used front-end downloading method, follow-up will continue to have a good way to add!

 

Published 48 original articles · won praise 33 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_33207292/article/details/104474337