本SDK提供GetObjectCommand
类实现文件下载。完整代码详见 Github 。
GetObjectCommand
调用的 S3 API 为 GetObject, 具体参见GetObject API 文档。
参数说明
Bucket
: 文件所在的存储空间Key
: 文件在存储空间内的名称
示例
执行该示例前请确保配置文件的正确性
以下代码段需要在上下文中运行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const s3 = require('./s3Client');
const { GetObjectCommand } = require("@aws-sdk/client-s3");
const fs = require('fs');
const path = require('path');
async function downloadFile(bucketName, keyName, downloadPath) {
try {
const params = {
Bucket: bucketName,
Key: keyName
};
const command = new GetObjectCommand(params);
const response = await s3.send(command);
const stream = response.Body;
const filePath = path.resolve(downloadPath, keyName);
const writeStream = fs.createWriteStream(filePath);
stream.pipe(writeStream);
return new Promise((resolve, reject) => {
writeStream.on('finish', () => {
console.log("File downloaded successfully to", filePath);
resolve(filePath);
});
writeStream.on('error', (err) => {
console.error("Error downloading file", err);
reject(err);
});
});
} catch (err) {
console.error("Error downloading file", err);
throw err;
}
}
在
Example/
目录中运行以下命令执行该示例
1
$ node GetObject.js <bucketName> <keyName> <downloadPath>