H5 PC 下载PDF ZIP 文件 针对微信兼容处理方案

59 阅读2分钟

dc68cf1421a78d9c610b0c26563baa18.png 第一种方案

  • 兼容PC、H5 ( 微信做了处理 IOS当前版本低于15【' 没有微信安全策略 '】/ 安卓所有设备 ) 不兼容可以根据需求引导用户打开引导弹窗
  downloadAsPdfOrZip(apiPath, fileUrls, this.zipUrl)
                .then((result) => {
                     if (result && result.needWxGuide) {
                        this.showWxGuide = true; // 弹出微信引导弹窗
                        this.$nextTick(() => this.downloadLoading = false);
                     }
                })
export function downloadAsPdfOrZip(apiPath, fileUrls, zipUrl) {
  if (!fileUrls || fileUrls.length === 0) {
    return Promise.reject(new Error('No files to download'));
  }

  const userAgent = navigator.userAgent;
  const isWeChat = /MicroMessenger/i.test(userAgent);
  const isAndroid = /Android|Adr/i.test(userAgent);
  const isIOS = /iPhone|iPad|iPod/i.test(userAgent);
  const isSingle = fileUrls.length === 1;

  let isIOSShouldUseDirectLink = false;
  if (isIOS) {
    const iosMatch = userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
    if (iosMatch) {
      const major = parseInt(iosMatch[1], 10);
      if (major < 15) {
        isIOSShouldUseDirectLink = true;
      }
    } else {
      isIOSShouldUseDirectLink = true;
    }
  }

  if (isAndroid || isIOSShouldUseDirectLink) {
    const downloadUrl = isSingle ? fileUrls[0] : zipUrl;

    if (!downloadUrl) {
      console.warn('downloadUrl is missing');
      return Promise.reject(new Error('Missing download URL'));
    }

    if (isWeChat) {
      console.log('🚀 微信环境:触发引导弹窗');
      return Promise.resolve({ needWxGuide: true });
    } else {
      try {
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.target = '_blank';
        a.rel = 'noopener';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        console.warn('window.open failed, fallback to direct open');
        window.open(downloadUrl, '_blank');
      }
      return Promise.resolve();
    }
  }

第二种方案

  • 兼容PC、H5 ( 微信做了处理 IOS当前版本低于15【' 没有微信安全策略 '】/ 安卓所有设备 ) 不兼容直接复制当前链接 ;弹窗让用户去游览器粘贴!

// // ✅ 新版 downloadAsPdfOrZip:兼容全平台(特别修复 iOS 14 下载无反应)
// export function downloadAsPdfOrZip(apiPath, fileUrls, zipUrl) {
//   if (!fileUrls || fileUrls.length === 0) {
//     return Promise.reject(new Error('No files to download'));
//   }

//   const userAgent = navigator.userAgent;
//   const isWeChat = /MicroMessenger/i.test(userAgent);
//   const isAndroid = /Android|Adr/i.test(userAgent);
//   const isIOS = /iPhone|iPad|iPod/i.test(userAgent);
//   const isSingle = fileUrls.length === 1;

//   // ========================
//   // 【修复】iOS 14 及以下(<15)不支持 Blob 下载,需走直链
//   // ========================
//   let isIOSShouldUseDirectLink = false;
//   if (isIOS) {
//     const iosMatch = userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
//     if (iosMatch) {
//       const major = parseInt(iosMatch[1], 10);
//       // iOS 15+ 才可靠支持 <a download> + Blob
//       if (major < 15) {
//         isIOSShouldUseDirectLink = true;
//       }
//     } else {
//       // 无法解析版本 → 保守走直链
//       isIOSShouldUseDirectLink = true;
//     }
//   }

//   // ========================
//   // Android 或 iOS < 15:走直链方案(含微信特殊处理)
//   // ========================
//   if (isAndroid || isIOSShouldUseDirectLink) {
//     const downloadUrl = isSingle ? fileUrls[0] : zipUrl;

//     if (!downloadUrl) {
//       alert('下载链接未生成,请稍后再试');
//       return Promise.reject(new Error('Missing download URL'));
//     }

//     if (isWeChat) {
//       copyTextToClipboard(downloadUrl);
//       alert('下载链接已复制,请在浏览器中粘贴下载');
//     } else {
//       // 非微信环境:尝试直接打开(Safari/Chrome on iOS 14 可能预览 PDF,ZIP 会提示下载)
//       window.open(downloadUrl, '_blank');
//     }
//     return Promise.resolve();
//   }

//   // ========================
//   // iOS 15+ / PC / 现代浏览器:走 POST + Blob 下载
//   // ========================
//   const fileName = isSingle ? '福利资料.pdf' : '福利资料.zip';
//   return downloadFilePost(apiPath, { fileUrls })
//     .then(blob => {
//       if (blob.type === 'text/html' || blob.size < 100) {
//         throw new Error('Invalid file response');
//       }

//       const url = URL.createObjectURL(blob);
//       const a = document.createElement('a');
//       a.href = url;
//       a.download = fileName;
//       document.body.appendChild(a);
//       a.click();
//       document.body.removeChild(a);
//       URL.revokeObjectURL(url);
//       return blob;
//     })
//     .catch(err => {
//       console.error('Download failed:', err);
//       alert('下载失败,请重试');
//       throw err;
//     });
// }

// function copyTextToClipboard(text) {
//   // 优先使用 Clipboard API(安全上下文)
//   if (navigator.clipboard && window.isSecureContext) {
//     navigator.clipboard.writeText(text).catch(() => { /* 静默失败 */ });
//     return;
//   }

//   // 降级方案:使用不可编辑元素避免拉起键盘
//   const fakeElem = document.createElement('span');
//   fakeElem.textContent = text;
//   fakeElem.style.cssText = `
//     position: fixed;
//     top: -9999px;
//     left: -9999px;
//     width: 1px;
//     height: 1px;
//     overflow: hidden;
//     opacity: 0;
//     user-select: all;
//     -webkit-user-select: all;
//     white-space: pre;
//   `;
//   document.body.appendChild(fakeElem);

//   const range = document.createRange();
//   range.selectNode(fakeElem);
//   const selection = window.getSelection();
//   selection.removeAllRanges();
//   selection.addRange(range);

//   let copied = false;
//   try {
//     copied = document.execCommand('copy');
//   } catch (err) {
//     // 忽略错误
//   }

//   selection.removeAllRanges();
//   document.body.removeChild(fakeElem);

// }