2017-12-18 285 views
0

我从JSON内容中即时创建一个CSV文件,并在S3存储区上传生成的CSV文件,而不是先在本地保存文件。如何使用NodeJS在S3 Bucket上上传CSV文件?

下面是我的代码片段,使用下面的代码我上传到S3存储桶的CSV文件,但它似乎并不是正确的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,[]); 
    } 
} 

请让我们知道上面的代码是怎么了。

回答

0

在你的params中添加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) 
       } 
      }); 
}); 
+0

我试过使用上面的标题,但它没有提供给我正确的结果。 –

+0

你能ping我错误 – Vipul

+0

嗨我再次尝试使用上述标题,它的工作原理,我在一个单独的评论中添加了整个代码。谢谢 –

1

您好我下面报头值再次尝试,它为我工作。下面是代码:

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); 
    } 
});