2016-12-12 78 views
0

我试图从Node.js托管的应用程序中从Amazon S3存储桶下载文件。使用Node.js从EC2实例下载AWS S3文件

var folderpath= process.env.HOME || process.env.USERPROFILE // tried using os.homedir() also 

var filename = 'ABC.jpg'; 
var filepath = 'ABC'; 

AWS.config.update({ 
    accessKeyId: "XXX", 
    secretAccessKey: "XXX", 
    region: 'ap-southeast-1' 
}); 

    var DOWNLOAD_DIR = path.join(folderpath, 'Downloads/'); 

    var s3 = new AWS.S3(); 
    var s3Params = {Bucket: filepath,Key: filename, }; 

    var file = require('fs').createWriteStream(DOWNLOAD_DIR+ filename); 
    s3.getObject(s3Params).createReadStream().pipe(file); 

此代码工作正常在本地主机,但因为实例FOLDERPATH回报不从实例工作“的/ home/EC2用户”,而不是用户的机器中下载文件夹的路径,即类似“C:\用户\名称”。

请问我该如何下载文件到用户机器?如何从ec2实例获取用户主目录的路径?

谢谢。

+2

作为一个方面说明:将secretAccessKey保存在代码中是一个坏主意。您应该创建IAM角色并将其分配给EC2实例。 –

+0

好的,我会的。谢谢@Sergey Kovalev –

+2

你是什么意思的“不工作”?你有错误吗? 'folderpath'是Linux机器上的一个正常目录路径(它是'ec2-user'的主目录)。你确定'/ home/ec2-user/Downloads /'目录是否存在,并且用户有写入权限? – GilZ

回答

1

您可以使用express来创建http服务器和API。您可以在Express.js入门中找到大量教程。 express.js的初始设置完成后,你可以做这样的事情在Node.js的代码:

AWS.config.update({ 
    accessKeyId: "XXX", 
    secretAccessKey: "XXX", 
    region: 'ap-southeast-1' 
}); 
var s3 = new AWS.S3(); 

app.get('/download', function(req, res){ 
    var filename = 'ABC.jpg'; 
    var filepath = 'ABC'; 
    var s3Params = {Bucket: filepath, Key: filename}; 
    var mimetype = 'video/quicktime'; // or whatever is the file type, you can use mime module to find type 

    res.setHeader('Content-disposition', 'attachment; filename=' + filename); 
    res.setHeader('Content-type', mimetype); 

    // Here we are reading the file from S3, creating the read stream and piping it to the response. 
    // I'm not sure if this would work or not, but that's what you need: Read from S3 as stream and pass as stream to response (using pipe(res)). 
    s3.getObject(s3Params).createReadStream().pipe(res); 
}); 

一旦做到这一点,你可以调用这个API /download,然后下载用户的计算机上的文件。根据您在前端使用的框架或库(或纯JavaScript),可以使用此/download api下载文件。只是谷歌,如何使用XYZ(框架)下载文件。

+0

它返回文件的数据意味着我仍然在angular.js中写入文件,这可能导致找到路径并提供给createWriteStream() –

+0

非常感谢您的时间和精力,但我认为使用易于使用的网址会很方便。 –