通过 GetObject 方法可以从指定桶中下载对象。在使用此接口之前,确保拥有对此对象的读访问权限。在使用下载接口的过程中可以通过设置进度条回调来获取目前下载数据进度信息。
tos:GetObject
权限,详细信息,请参见权限配置指南。tos:GetObjectVersion
权限,详细信息,请参见权限配置指南。以下示例代码用于获取 examplebucket 中 exampleobject.txt 文件的预览和下载 URL。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="upload">上传</button>
<button id="preview">获取预览Url</button>
<button id="download">获取下载Url</button>
<input id="file" type="file" />
<!-- 导入 SDK 文件 -->
<script src="https://tos-public.volccdn.com/obj/volc-tos-public/@volcengine/tos-sdk@latest/browser/tos.umd.production.min.js"></script>
<script src="./const.js"></script>
<script type="text/javascript">
const client = new TOS({
// yourRegion 填写 Bucket 所在地域。以华北2(北京)为例,yourRegion 填写为 cn-beijing。
region: yourRegion,
// 填写 endpoint 名称。
endpoint: yourEndpoint,
// 从 STS 服务获取的临时访问密钥(AccessKey ID 和 AccessKey Secret)。
accessKeyId: yourAccessKey,
accessKeySecret: yourSecretKey,
// 从 STS 服务获取的安全令牌(SecurityToken)。
stsToken: yourSecurityToken,
// 填写 Bucket 名称。
bucket: examplebucket,
});
const name = 'exampledir/exampleobject.txt';
const upload = document.getElementById('upload');
upload.addEventListener('click', async () => {
// 从输入框获取 file 对象,例如 <input type="file" id="file" />。
const data = document.getElementById('file').files[0];
console.log('data', data);
try {
// 分片大小最小为 5MB
const partSize = 5 * 1024 * 1024;
const result = await client.uploadFile({
key: name,
file: data,
// 上传时指定分片大小
partSize,
});
console.log(result);
} catch (e) {
console.log(e);
}
});
// 获取文件预览的 URL
const preview = document.getElementById('preview');
preview.addEventListener('click', async () => {
try {
// 设置 URL 的有效时长为 3600 秒。如果不设置时长,默认是 1800 秒。
const result = await client.getPreSignedUrl({
key: name,
expires: 3600,
});
console.log(result);
} catch (e) {
console.log(e);
}
});
// 获取文件的下载 URL
const download = document.getElementById('download');
download.addEventListener('click', async () => {
try {
// 设置 URL 的有效时长为 3600 秒。如果不设置时长,默认是 1800 秒。
const filename = '中文examplefile.txt';
const result = await client.getPreSignedUrl({
key: name,
expires: 3600,
// 配置响应头实现通过 URL 访问时自动下载文件,并设置下载后的文件名称。
response: {
contentDisposition: `attachment; filename=${filename}`,
},
});
console.log(result);
} catch (e) {
console.log(e);
}
});
</script>
</body>
</html>