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

从服务器获取Base64编码Zip文件后保存损坏,求解决方法

问题

从GitLab API接收Base64编码的Zip文件,解码后用JSZip能读取其中的main.py内容,但保存为test.zip后文件损坏无法打开。以下是可复现的Node.js代码:

const fs = require(`fs`)
const fetch = require(`node-fetch`)
const JSZip = require(`jszip`)

function logMainFile(blob){
  const zip = new JSZip();
  zip.loadAsync(blob).then(function(zip) {
    zip.file(`main.py`).async(`string`).then(function (content) {
      console.log(content);
    });
  })
}

async function getFileFromGitlab() {
  const url = `https://gitlab.com/api/v4/projects/47987400/repository/files/products%2Fcuore%2Fcuore.zip?ref=main`

  const text = await fetch(url)
  const data = await text.json()
  const blob = atob(data?.content);

  // This is here just to show the data is there
  logMainFile(blob)

  fs.writeFileSync(`test.zip`, blob)

}

getFileFromGitlab()
错误原因与修复

问题出在**atob解码后得到的是UTF-8字符串,直接写入文件会破坏Zip的二进制数据**。Zip属于二进制文件,必须用二进制格式保存,不能通过字符串中转。

修改后的代码:

const fs = require(`fs`)
const fetch = require(`node-fetch`)
const JSZip = require(`jszip`)

function logMainFile(blob){
  const zip = new JSZip();
  zip.loadAsync(blob).then(function(zip) {
    zip.file(`main.py`).async(`string`).then(function (content) {
      console.log(content);
    });
  })
}

async function getFileFromGitlab() {
  const url = `https://gitlab.com/api/v4/projects/47987400/repository/files/products%2Fcuore%2Fcuore.zip?ref=main`

  const res = await fetch(url)
  const data = await res.json()
  // 直接将Base64字符串转为Buffer(二进制数据)
  const zipBuffer = Buffer.from(data.content, 'base64');

  logMainFile(zipBuffer)

  fs.writeFileSync(`test.zip`, zipBuffer)
}

getFileFromGitlab()

核心说明:

  • atob会把Base64转成UTF-8字符串,这个过程中二进制字节会被错误编码,导致Zip文件结构损坏。
  • 使用Buffer.from(data.content, 'base64')直接将Base64字符串转换为Node.js的Buffer类型,这是二进制数据的正确载体,写入文件后就能得到完整可用的Zip文件。
  • JSZip支持直接处理Buffer,所以logMainFile函数无需修改,传入Buffer依然能正常读取main.py内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:15:03