我正在将base64
编码值写入zip文件。以下代码用于撰写:
var base64Data = base64_encoded_value;
base64Data += base64Data.replace('+', ' ');
binaryData = new Buffer(base64Data, 'base64').toString('binary');
fs.writeFile('test.zip', binaryData, "binary", function (err) {
console.log(err); // writes out file without error
});
它的工作和test.zip
文件正在创建,问题是当我提取它时,它给了我以下错误:
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of /home/user/Node/project/public/media/written/zip4045508057.zip or
/home/user/Node/project/public/media/written/zip4045508057.zip.zip, and cannot find /home/user/Node/project/public/media/written/zip4045508057.zip.ZIP, period.
有没有办法做到这一点?
答案 0 :(得分:1)
您必须将 base64 转换为 utf8 格式。然后您可以使用转换后的数据来写入文件。
尝试使用以下函数将 base64 字符串转换为 utf8
/**
* @param b64string {String}
* @returns {Buffer}
*/
function _decodeBase64ToUtf8(b64string) {
var buffer;
if (typeof Buffer.from === "function") {
// Node 5.10+
buffer = Buffer.from(b64string, 'base64');
} else {
// older Node versions
buffer = new Buffer(b64string, 'base64');
}
return buffer;
}
我用它来使用 base64 数据
创建ZIP文件答案 1 :(得分:0)
从base64字符串中提取.zip文件的另一种方法是使用npm软件包mws-extract-document
const mwsExtract = require('mws-extract-document');
const dist = './folder/to/document.zip';
const base64String = ''; //located at PdfDocument data response from MWS api.
// PROMISE
mwsExtract(base64String, dist)
.then((msg)=>{
// file saved. do something here...
console.log(msg);
})
.catch(err)=>{
console.log(err);
});