【问题标题】:S3 Upload with Excel data using Node.jsS3 使用 Node.js 上传 Excel 数据
【发布时间】:2021-05-26 12:07:15
【问题描述】:

我正在尝试使用 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;
        }
    });

【问题讨论】:

    标签: node.js excel amazon-s3 aws-sdk xlsx


    【解决方案1】:

    所以我在客户端使用 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]);
    

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2015-11-17
      • 2021-06-13
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多