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

Node.js与Python中字节数组转PDF失败:生成文件损坏问题

字节数组转PDF文件损坏问题解决

我们调用一个以字节数组形式返回PDF文件的API,尝试将响应的字节数组转换为PDF文件,但生成的文件损坏无法正常打开。Node.js和Python两种实现方式都遇到了同样的问题。

原错误代码

Node.js 实现

const axios = require('axios')
const fs = require('fs')
const {Base64} = require('js-base64');

axios.post("some api....")
  .then((response) => {
    var u8 = new Uint8Array(response.data.success);
    var decoder = new TextDecoder('utf8');
    var b64encoded = btoa(decoder.decode(u8));

    var bin = Base64.atob(b64encoded);
    fs.writeFile('file.pdf', bin, 'binary', error => {
        if (error) {
            throw error;
        } else {
            console.log('binary saved!');
        }
    });
  })

Python 实现

import requests
import json
import base64

url = 'some api....'

x = requests.post(url, json = {})

# print(x.json()['success'])

dataStr = json.dumps(x.json()['success'])

base64EncodedStr = base64.b64encode(dataStr.encode('utf-8'))

with open('file.pdf', 'wb') as theFile:
  theFile.write(base64.b64decode(base64EncodedStr))

问题根源

API返回的是原始PDF二进制数据的数值数组(示例格式:[84,47,81,57,67,85,...]),但原代码错误地对这个数组做了多余的文本编码/解码操作:

  • Node.js里用UTF-8解码二进制数组,再转Base64来回折腾,破坏了原始二进制结构
  • Python里把数组转成JSON字符串再做Base64编码,相当于把数组的文本表示转成了Base64,解码后根本不是原始PDF数据

正确实现代码

Node.js 正确写法

const axios = require('axios')
const fs = require('fs').promises;

axios.post("你的API地址", {}, { responseType: 'json' })
  .then(async (response) => {
    // 直接将API返回的字节数值数组转成Buffer
    const pdfBuffer = Buffer.from(response.data.success);
    await fs.writeFile('file.pdf', pdfBuffer);
    console.log('PDF文件保存成功');
  })
  .catch(error => {
    console.error('请求或保存失败:', error);
  });

Python 正确写法

import requests

url = '你的API地址'

response = requests.post(url, json={})
# 获取API返回的字节数值数组
byte_values = response.json()['success']

# 将数值数组直接转成bytes对象
pdf_bytes = bytes(byte_values)

with open('file.pdf', 'wb') as the_file:
    the_file.write(pdf_bytes)

核心逻辑就是:直接把API返回的数值数组转换成对应类型的二进制对象(Node.js的Buffer、Python的bytes),然后写入文件即可,不需要任何多余的编码转换步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:01:13