uniapp mobile H5 download file xls implementation

background:

The current project is built using H5 and uniapp on the mobile side. The requirements are: the background port returns the file binary file, and the file download is implemented in the mobile browser. Several ports of uniapp do not support H5.

uni.downloadFile(OBJECT)

After using the download above:

#1 uni.saveFile(OBJECT) does not support H5

# 2 uni.openDocument(OBJECT) does not support H5

solution:

Use the native H5 <a> tag and add an XMLHttpRequest request to complete the download.

final effect:

Source code:

.vue

<template>
 <u-button class="dl-btn" style="width:670rpx;" @click="handleBtnEvent" :disabled="!downloadEnable"
              :data-action="false">下载对账单
    </u-button>
</template>

<script>
export default{
data(){
return {url}
},
methods(){
handleBtnEvent(e) {//ok
      if (e.target.dataset.action) {
        console.log('支付')
      } else {
        console.log('|-------下载,start')
        let url = `${uni.getStorageSync('serverName')}/msmstr/file?`
        this.url = url
        downLoadFileH5(this.url)
        }
    },
},
 downLoadFileH5 = (url, name = 'download', type = '文件') => {
  /*#ifdef H5*/
  console.log('|--下载')
  uni.showLoading({title: '正在下载..'})
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer'; // 返回类型blob
  xhr.onload = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log('|--下载完成', this)
      uni.hideLoading()
      uni.showToast({title:'下载完成'})
      let blob = this.response;
      // 转换一个blob链接
      // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串),
      // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
      let downLoadUrl = ''
      if (type === '视频') {
        downLoadUrl = window.URL.createObjectURL(new Blob([blob], {
          type: 'video/mp4'
        }));
      } else if (type === '图片' || type === '文件') {
        downLoadUrl = url
      }
      // 视频的type是video/mp4,图片是image/jpeg
      // 01.创建a标签
      let a = document.createElement('a');
      // 02.给a标签的属性download设定名称
      a.download = name;
      // 03.设置下载的文件名
      a.href = downLoadUrl;
      // 04.对a标签做一个隐藏处理
      a.style.display = 'none';
      // 05.向文档中添加a标签
      document.body.appendChild(a);
      // 06.启动点击事件
      a.click();
      // 07.下载完毕删除此标签
      a.remove();
    }

  };
  xhr.send()
  /*#endif*/
},
}
}
</script>
  

Guess you like

Origin blog.csdn.net/LlanyW/article/details/135339762