React项目下载服务端生成的pkpass苹果钱包通行证文件失效问题求解
问题根源
前端请求默认将响应体按UTF-8文本解析,二进制格式的pkpass文件在强制转文本的过程中字节被重编码,原本的单字节二进制内容被转为多字节UTF-8字符,导致最终生成的文件体积翻倍、内容损坏,无法被识别为合法的通行证文件。
解决方案
仅需要修改前端请求逻辑,核心是指定二进制响应类型,修正后的代码如下:
// 以axios为例,核心新增responseType: 'blob'配置项 .get(`/appleWalletCard/${user.me._id}`, { responseType: 'blob' }) .then((response: any) => { if (response) { // 创建Blob时显式指定pkpass对应的MIME类型 const file = new Blob([response.data], { type: 'application/vnd.apple.pkpass' }) const fileURL = URL.createObjectURL(file) const link = document.createElement('a') link.href = fileURL // 必须指定.pkpass后缀的文件名,保证系统识别文件格式 link.download = 'walletPass.pkpass' link.click() // 释放ObjectURL避免内存泄漏 URL.revokeObjectURL(fileURL) } })
如果使用原生fetch实现,写法参考如下:
fetch(`/appleWalletCard/${user.me._id}`) .then(res => res.blob()) .then(blob => { const fileURL = URL.createObjectURL(blob) const link = document.createElement('a') link.href = fileURL link.download = 'walletPass.pkpass' link.click() URL.revokeObjectURL(fileURL) })
内容的提问来源于stack exchange,提问作者user2675468
相关产品推荐
相关产品推荐

