PDF下载兼容IOS和Android两端

756 阅读1分钟

手机端(H5)需要下载PDF文件

// 下载pdf
      downloadPdf(pdfsrc, fileName) {
        // iOS端用buffer 处理
        let xhr = new XMLHttpRequest();
        xhr.open('get', pdfsrc, true);
        const that = this;
        if (this.curSystem === 'ios') {
          xhr.responseType = 'arraybuffer';
        } else {
          xhr.setRequestHeader('Content-Type', `application/pdf`);
          xhr.responseType = 'blob';
        }

        xhr.onload = function () {
          if (this.status == 200) {
            console.log('arraybuffer---', this.response, that.curSystem);
            //接受二进制文件流
            let blob = this.response;
            if (that.curSystem === 'ios') {
              const blobRes = this.response;
              blob = new Blob([blobRes], {
                type: 'application/octet-stream',
                'Content-Disposition': 'attachment'
              });
            }
            const blobUrl = window.URL.createObjectURL(blob);
            let a = document.createElement('a');
            let event = new MouseEvent('click');
            a.download = fileName || 'pdf-' + new Date().getTime();
            a.href = blobUrl;
            a.dispatchEvent(event); // 触发a的单击事件
          }
        };
        xhr.send();
      },

说明:

在IOS端可以使用buffer类型做兼容,在安卓端使用 blob ;