我从服务器收到一个 Base64 编码的 zip 文件,我必须保存它。
之后,如果我
atob(content)
,它看起来像这样:
可与节点一起运行的最小可重现代码:
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()
问题是我无法打开该文件,它似乎已损坏。我做错了什么?
我发现了问题,我只需在保存之前将其转换为字节即可。我用的是
function str2bytes (str: string) {
const bytes = new Uint8Array(str.length)
for (let i=0; i<str.length; i++) {
bytes[i] = str.charCodeAt(i)
}
return bytes
}