我正在尝试从我的Node.js托管应用程序下载Amazon 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);
此代码在localhost上正常工作但在实例中不起作用,因为在实例文件夹路径返回" / home / ec2-user"而不是用户机器的下载文件夹路径,例如" C:\ Users \ name"。
请建议我如何将文件下载到用户的机器?如何从ec2实例获取用户主目录的路径?
谢谢。
答案 0 :(得分: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下载该文件。只是google,如何使用XYZ(框架)下载文件。