node.js - S3 使用 Node.js 上传 Excel 数据
问题描述
我正在尝试使用 Node.js 和 aws-sdk 将 excel 文件上传到 S3
输入是 JSON,我正在使用 XLSX 库将其转换为工作簿并使用以下代码上传到 S3。
const wb = XLSX.utils.book_new();
//Convert JSON to sheet data
const sheetData = XLSX.utils.json_to_sheet(req.body);
XLSX.utils.book_append_sheet(wb, sheetData, 'Sheet 1');
const sheetDataBuffer = XLSX.write(wb, {bookType: 'xlsx', type: 'buffer', bookSST: false});
const s3 = new AWS.S3();
s3.upload({
Key: file,
Bucket: <bucket name>,
Body: sheetDataBuffer,
ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
ContentEncoding: 'base64'
}).promise()
.then(data => {
logger.debug("uploaded the data");
res.sendStatus(200);
});
}
但是,当我在 S3 上查看上传的文件时,它会显示乱码/损坏的数据。我错过了什么?这是内容编码问题吗?
更新:看起来我正在使用的客户端解析库——Papaparse——将 excel 内容解析为乱码。我尝试将编码选项设置为“utf-8”,但没有帮助。知道我错过了什么吗?
Papa.parse(e.target.files[0], {
encoding: 'utf-8',
download: true,
complete: async data => {
// data.data is garbled
const response = await fetch('/<apipath>', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data.data
});
const res = await response;
}
});
解决方案
所以我想出了在客户端使用 XSLX 库(不再使用 Papaparse),以防它帮助某人。
const reader = new FileReader();
reader.onload = async (evt) => {
const bstr = evt.target.result;
const wb = XLSX.read(bstr, {type:'binary'});
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
//data is parsed correctly
const data = XLSX.utils.sheet_to_json(ws, {header:1});
const response = await fetch('/<apipath>', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
const res = await response;
};
reader.readAsBinaryString(e.target.files[0]);
推荐阅读
- javascript - 使用javascript将日期时间字段(在json对象中)转换为毫秒
- dialogflow-es - 当要求向谷歌助手启动我的应用程序时,我收到一条关于谷歌共享数据阻止启动应用程序的消息
- c - 为什么 int 可以容纳 10 位数字但不能处理另一个整数的 9 位数字?
- python - python在磁盘上存储一个实时变量
- angular - 如何在 Angular 中为 prod 和 test 设置不同的 dist 文件夹
- angular - Angular RxJs Observable 可用作字符串,但不能用作接口或类
- bash - bash中stdout和stderr之间的顺序不匹配
- android - 不需要添加支持库来制作recyclerView的方式
- shell - 如何分隔同一字符串中同一字符的多次出现
- javascript - 解构内部反应组件的最佳方法?