如何在Lambda中使用S3存储桶签名的URL读取Excel数据?

时间:2019-01-03 10:46:08

标签: javascript node.js amazon-web-services amazon-s3 aws-lambda

我在s3存储桶中存储了一个文件,并编写了lambda函数来给我们提供签名的URL,然后尝试使用xlsx从签名的URL中读取数据。但是它不起作用,下面的代码是:

exports.handler = (event, context, callback) => {
var params = {
  Bucket: "abc", 
  Key: "xyz.xls"
};
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var url = s3.getSignedUrl('getObject', params, function(err,data){
  if(err){
    console.log(err, err.stack);
    callback(err,null);
  }else{
    var XLSX = require('xlsx')
    var workbook = XLSX.readFile(data);
    var sheet_name_list = workbook.SheetNames;
    var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[2]]);  
    var res = {
        statusCode:200,
        body:JSON.stringify(xlData)
    }
    callback(null,res);
  }
});
};

无法读取文件。找不到文件错误,甚至在浏览器中也会抛出同样的URL异常。谢谢

1 个答案:

答案 0 :(得分:0)

看起来您需要这样的东西:

var XLSX = require('xlsx'), request = require('request');
request(url, {encoding: null}, function(err, res, data) {
    if(err || res.statusCode !== 200) {
        callback(err,null);
        return;
    }

    /* data is a node Buffer that can be passed to XLSX.read */
    var workbook = XLSX.read(data, {type:'buffer'});
    var sheet_name_list = workbook.SheetNames;
    var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[2]]);  
    var res = {
        statusCode:200,
        body:JSON.stringify(xlData)
    }
    callback(null,res);
});