PDF URL转Base64失败:生成的Base64无法打开怎么解决?
问题描述
我尝试将PDF的URL转换为Base64编码,参考其他问题找到了如下解决方案,但在我的场景中无法生效:
convertToBase64(info: any, url: string) { this.http.get(url, { responseType: "blob" }) .subscribe(blob => { console.log("blob ", blob) const reader = new FileReader(); const binaryString = reader.readAsDataURL(blob); reader.onload = (event: any) => { //Here you can do whatever you want with the base64 String console.log("File in Base64: ", event.target.result); this.pdfBase64 = event.target.result this.service.sendMail(info, this.pdfBase64) .subscribe((data) => { console.log("data ", data) }) }; reader.onerror = (event: any) => { console.log("File could not be read: " + event.target.error.code); }; }); }
我使用在线工具编码该PDF URL得到的Base64是正常的(可用于发送邮件并正常打开),但上述代码生成的Base64更短,且打开时报错。请问如何正确将PDF URL转换为Base64?
解决方案
你的代码核心问题是事件绑定顺序错误:FileReader.readAsDataURL是异步操作,你先调用了读取方法,再绑定onload事件,这可能导致读取完成后回调还未注册,最终获取到不完整或无效的Base64结果。
修正后的代码
convertToBase64(info: any, url: string) { this.http.get(url, { responseType: "blob" }) .subscribe(blob => { console.log("blob ", blob); const reader = new FileReader(); // 先绑定onload/onerror事件,再执行读取操作 reader.onload = (event: any) => { console.log("File in Base64: ", event.target.result); // 如果后端需要纯Base64字符串(不含data:前缀),可以拆分处理 // this.pdfBase64 = event.target.result.split(',')[1]; this.pdfBase64 = event.target.result; this.service.sendMail(info, this.pdfBase64) .subscribe((data) => { console.log("data ", data); }); }; reader.onerror = (event: any) => { console.log("File could not be read: " + event.target.error.code); }; // 最后调用读取方法 reader.readAsDataURL(blob); }); }
额外检查点
- 确认Blob完整性:打印
blob.size,对比在线工具下载的PDF文件大小,确保HTTP请求完整获取了文件内容。 - Base64前缀处理:
readAsDataURL生成的结果包含data:application/pdf;base64,前缀,如果你的邮件服务需要纯Base64编码内容,需要通过split(',')[1]去除前缀。 - 跨域验证:如果PDF URL属于外部域名,确保目标服务器配置了CORS允许你的域名访问,否则HTTP请求可能获取到不完整的响应。
内容的提问来源于stack exchange,提问作者Jack23
相关产品推荐
相关产品推荐

