如何使用NodeJS在S3 Bucket上传CSV文件?

问题描述 投票:1回答:2

我正在从JSON内容动态创建CSV文件,并在S3存储桶上传生成的CSV文件,而不是先在本地保存文件。

下面是我的代码片段,因为使用下面的代码将我的CSV文件上传到S3存储桶上,但它似乎没有正确的CSV格式。

var uploadCSVFileOnS3Bucket = function(next, csvFileContent,results) {
    console.log("uploadCSVFileOnS3Bucket function started");
    var bufferObject = new Buffer.from(JSON.stringify(csvFileContent));
    var filePath = configurationHolder.config.s3UploadFilePath;
    var s3 = new AWS.S3();
    var params = {
        Bucket: 'bucket_name'
        Key: 's3UploadFilePath',
        Body: bufferObject,
        CacheControl:'public, max-age=86400'
    }
    s3.upload(params, function(err, data) {
        if (err) {
            console.log("Error at uploadCSVFileOnS3Bucket function",err);
            next(err);
        } else {
            console.log("File uploaded Successfully");
            next(null, filePath);
        }
    });
};

另外,我使用“json2csv”npm模块从JSON生成csv文件内容。

以下是代码:

var generateCSVFile = function(next,callback,csvFileContent) {
   console.log("generateCSVFile function started",csvFileContent);
   if(csvFileContent && csvFileContent.length>0) {
     var fields = ['field1','field2','field3',........];
     var csv = json2csv({ data: csvFileContent, fields: fields });
     console.log('created',csv);
     next(null,csv);
   }
   else {
     next(null,[]);
   }
 }

请告诉我们上述代码出错的地方。

node.js csv amazon-web-services amazon-s3
2个回答
2
投票

嗨,我再次尝试使用以下标题值,它对我有用。以下是代码:

var s3 = new AWS.S3();
var params = {
    Bucket: bucketName,
    Key: filePath,
    Body: csvFileContent,
    ContentType: 'application/octet-stream',
    ContentDisposition: contentDisposition(filePath, {
        type: 'inline'
    }),
    CacheControl: 'public, max-age=86400'
}
s3.putObject(params, function(err, data) {
    if (err) {
        console.log("Error at uploadCSVFileOnS3Bucket function", err);
        next(err);
    } else {
        console.log("File uploaded Successfully");
        next(null, filePath);
    }
});

0
投票

在你的参数中添加ContentDisposition:'attachment'。

否则你也可以阅读文件并上传到s3

fs.readFile(FILEPATH, function(err, file_buffer) {
            var params = {
                Bucket:  //bucketname,
                Key:key,
                ContentDisposition: 'attachment',
                Body: file_buffer
            };
            s3.upload(params, function(err, data) {
                if (err) {
                    console.log("Error in upload");
                    callback(err, null)
                }
                if (data) {
                    console.log("Upload Success", data);
                    callback(null, data)
                }
            });
});
© www.soinside.com 2019 - 2024. All rights reserved.