我正在尝试从我的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上工作正常,但不起作用,因为在实例上,folderpath返回"/home/ec2-user",而不是下载路径的用户计算机文件夹,即" c: users name"之类的东西。/p>
请建议我如何将文件下载到用户的计算机上?如何从EC2实例获取用户主目录的路径?
谢谢。
您可以使用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(框架)下载文件。