后端返回Uint8Array,前端新标签页展示PDF加载失败
问题解决:前端无法加载后端返回的PDF Uint8Array数据
问题根源
后端返回的Uint8Array在JSON序列化传输过程中被转换成了带数字索引的普通对象(即你看到的{0: 37, 1: 80, ...}结构),前端直接用这个对象创建Blob时,生成的文件并非有效的PDF格式,导致浏览器无法解析。
解决方案
方案1:前端将对象转换为Uint8Array
修改前端代码,把返回的data对象还原为真正的Uint8Array后再创建Blob:
if (result.success) { // 将带索引的对象转换为Uint8Array const pdfArray = new Uint8Array(Object.values(result.data)); const pdfBlob = new Blob([pdfArray], { type: 'application/pdf' }); const pdfURL = URL.createObjectURL(pdfBlob); window.open(pdfURL, '_blank'); }
方案2:后端返回Base64编码(更稳定)
如果前端转换仍存在兼容性问题,建议后端将Uint8Array转为Base64字符串返回,前端再解码处理:
后端代码修改:
try { const pdfBytes = await pdfDoc.save(); const filePath = './dddd.pdf'; fs.writeFileSync(filePath, pdfBytes); // 将Uint8Array转为Base64字符串 const pdfBase64 = Buffer.from(pdfBytes).toString('base64'); return pdfBase64; } catch (err) { console.log('error while saving'); console.log(err); }
前端代码修改:
if (result.success) { // 解码Base64为Uint8Array const binaryString = atob(result.data); const pdfArray = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { pdfArray[i] = binaryString.charCodeAt(i); } const pdfBlob = new Blob([pdfArray], { type: 'application/pdf' }); const pdfURL = URL.createObjectURL(pdfBlob); window.open(pdfURL, '_blank'); }
验证说明
后端本地用fs.writeFileSync能生成有效PDF,说明pdfBytes本身是正确的,问题完全出在传输过程中的格式转换环节,两种方案都能确保前端拿到有效的PDF字节数据,解决浏览器无法加载的问题。
内容的提问来源于stack exchange,提问作者IdoBa
相关产品推荐
相关产品推荐

