You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase如何将pdfFileFormat字符串以字节/uint数组形式上传至Firestore

核心问题原因

上传失败/上传后PDF无法渲染的根因是你获取到的data.message是PDF原始二进制字节的字符串形式,不属于合法UTF-8编码文本:

  • 直接用字符串创建Blob时,JS默认会按UTF-8对字符串做编码转换,会破坏PDF中FlateDecode压缩流等非文本二进制结构
  • 调用uploadString时不传编码参数,默认同样按UTF-8处理,同样会损坏文件结构
可行实现方案

方案1:转Uint8Array后通过uploadBytes上传(兼容性最好)

逐字符提取字节码生成无符号8位整型数组,完全规避UTF-8转码问题,代码可直接复用:

const uploadPDF = () => {
  if (!user) return;
  getInvoicePDFStringByInvoiceId('129', user.token).then((data) => {
    const pdfRawStr = data.message;
    // 逐字节转换,避免编码损坏
    const pdfBytes = new Uint8Array(pdfRawStr.length);
    for (let i = 0; i < pdfRawStr.length; i++) {
      pdfBytes[i] = pdfRawStr.charCodeAt(i) & 0xFF;
    }
    const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });
    const storageRef = ref(storage, `invoices/${user.uid}/129.pdf`);

    uploadBytes(storageRef, pdfBlob)
      .then(() => console.log('PDF上传成功'))
      .catch((error) => console.error('上传失败:', error.message));
  });
};

方案2:指定binary编码通过uploadString上传

uploadString原生支持二进制字符串上传,显式指定编码参数即可,不需要手动转Blob:

const uploadPDF = () => {
  if (!user) return;
  getInvoicePDFStringByInvoiceId('129', user.token).then((data) => {
    const storageRef = ref(storage, `invoices/${user.uid}/129.pdf`);
    // 第三个参数指定编码为binary,同时设置正确的contentType
    uploadString(storageRef, data.message, 'binary', {
      contentType: 'application/pdf'
    })
      .then(() => console.log('PDF上传成功'))
      .catch((error) => console.error('上传失败:', error.message));
  });
};
校验注意事项
  • 上传完成后不要只看成功回调,务必取文件下载链接在浏览器中直接打开,确认PDF能正常渲染
  • 如果接口返回的字符串中换行、特殊符号被转义(比如真实换行变成了字面量\\n),需要先做反转义处理再上传
  • 不需要额外做Base64编解码,保持原始字节结构即可正常渲染

内容的提问来源于stack exchange,提问作者Shivam Sahil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 08:12:11