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

上传至S3的PDF文件卢比符号(₹)丢失问题求助

解决S3上传PDF后卢比符号丢失的问题

核心问题分析

本地正常、EKS/API Gateway环境出错,根源在二进制文件的读取编码和ContentType配置错误:

  1. 用fs.readFileSync默认utf8编码读取PDF(二进制文件),会破坏原始字节流,本地环境编码兼容侥幸正常,但容器/网关环境的严格编码处理会导致特殊符号丢失。
  2. 给PDF指定charset=utf-8完全多余,PDF是二进制格式,这个声明会让S3或下游服务错误解析文件内容。

修复步骤

1. 正确读取PDF文件

读取二进制文件时,直接返回Buffer(不指定编码),避免编码转换破坏字节:

// 不指定encoding,默认返回Buffer,完美保留二进制数据
const content = fs.readFileSync(filePath);

(如果之前写了encoding: 'utf8',必须删掉)

2. 修正ContentType配置

去掉多余的charset=utf-8,保持纯application/pdf:

const uploadParams = {
  Bucket: bucket,
  Key: key,
  Body: content,
  ContentType: "application/pdf", // 只保留MIME类型
};

3. API Gateway额外配置(如果用网关上传)

API Gateway默认会把非文本类型转码,要添加二进制媒体类型:

  • 打开API Gateway控制台,找到目标API
  • 进入「设置」页面,在「二进制媒体类型」中添加application/pdf
  • 重新部署API,让配置生效

修改后的完整代码

const content = fs.readFileSync(filePath); // 默认返回Buffer

const uploadToS3UsingSdk = async (bucket, key, content) => {
  return new Promise((resolve, reject) => {
    const awsConfig = {
      accessKeyId: process.env.accessKeyId,
      secretAccessKey: process.env.secretAccessKey,
      region: process.env.region,
      apiVersion: "2006-03-01",
    };

    const s3 = new AWS.S3(awsConfig);

    const uploadParams = {
      Bucket: bucket,
      Key: key,
      Body: content,
      ContentType: "application/pdf",
    };

    s3.upload(uploadParams, function (err, data) {
      if (err) {
        console.log("Error", err);
        return reject({
          isSuccess: false,
          errorMessage: err.message || "上传失败",
          status: 500,
        });
      }
      if (data) {
        console.log("Upload Success", data.Location);
        return resolve({
          isSuccess: true,
          errorMessage: null,
        });
      }
    });
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:25:39