[英]How do you download a file from AWS S3 to a client's device?
Have looked at all the tutorials on how to download files from S3 to local disk.查看了有关如何将文件从 S3 下载到本地磁盘的所有教程。 I have followed all the solutions and what they do is download the file to the server and not to the client.我遵循了所有解决方案,他们所做的是将文件下载到服务器而不是客户端。 The code I currently have is我目前拥有的代码是
app.get('/download_file', function(req, res) {
var file = fs.createWriteStream('/Users/arthurlecalvez/Downloads/file.csv');
file.on('close', function(){console.log('done'); });
s3.getObject({ Bucket: 'data.pool.al14835', Key: req.query.filename }).on('error', function (err) {
console.log(err);
}).on('httpData', function (chunk) {
file.write(chunk);
}).on('httpDone', function () {
file.end();
}).send();
res.send('success')
})
How do I then send this to the client so that it is downloaded onto their device?然后我如何将其发送给客户端,以便将其下载到他们的设备上?
S3 supports the ability to generate a pre-signed URL via the AWS Javascript API. S3 支持通过 AWS Javascript API 生成预签名 URL 的能力。 Users can then GET
this URL to download the S3 object to their local device.然后,用户可以GET
此 URL 以将 S3 对象下载到他们的本地设备。
See this question for a Node.js
code sample.有关Node.js
代码示例,请参阅此问题。
you can use SignedURL Like that你可以像那样使用 SignedURL
var params = {Bucket: bucketname , Key: keyfile , Expires: 3600 , ResponseContentDisposition : `attachment; filename="filename.ext"` };
var url = s3.getSignedUrl('getObject', params);
the generated link will force download with the name filename.ext生成的链接将强制下载名为 filename.ext
If you have the file URL you can do it like that,如果你有文件 URL,你可以这样做,
new Observable((observer) => {
var xhr = new XMLHttpRequest();
xhr.open("get", fileURL, true);
xhr.responseType = "blob";
xhr.onload = function () {
if (xhr.readyState === 4) {
observer.next(xhr.response);
observer.complete();
}
};
xhr.send();
}).subscribe((blob: any) => {
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = elem.material.driverUrl;
link.click();
});
The file URL is: https://BucketName.Region.amazonaws.com/Key Just replace with your Bucket name, Region and Key文件 URL 为: https : //BucketName.Region.amazonaws.com/Key只需替换为您的存储桶名称、区域和密钥
您可以使用 res.download 方法http://expressjs.com/en/api.html#res.download吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.