首页 > 解决方案 > 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;
        }
    });

标签: node.jsexcelamazon-s3aws-sdkxlsx

解决方案


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

推荐阅读