更新时间:2024-11-07 GMT+08:00
分段相关接口概述(Harmony SDK)
对于较大文件上传,可以切分成段上传。用户可以在如下的应用场景内(但不仅限于此),使用分段上传的模式:
- 上传超过100MB大小的文件。
- 网络条件较差,和OBS服务端之间的链接经常断开。
- 上传前无法确定将要上传文件的大小。
分段上传分为如下3个步骤:
以下代码简单展示了分段上传的各个步骤:
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
// 引入依赖包 import ObsClient from '@obs/esdk-obs-harmony'; // 创建ObsClient实例 const obsClient = new ObsClient({ // 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险 // 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html AccessKeyId: process.env.ACCESS_KEY_ID, SecretAccessKey: process.env.SECRET_ACCESS_KEY, // 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入 // SecurityToken: process.env.SECURITY_TOKEN, // Server填写Bucket对应的Endpoint, 这里以华北-北京四为例,其他地区请按实际情况填写 Server: "https://obs.cn-north-4.myhuaweicloud.com", }); // 指定存储桶名称 const bucketName = "examplebucket"; // 指定对象,此处以 example/objectname 为例 const objectName = "example/objectname"; async function run() { try { // 初始化分段上传任务 const initiateMultipartUploadOutput = await obsClient.initiateMultipartUpload({ Bucket: bucketName, Key: objectName }); if (initiateMultipartUploadOutput.CommonMsg.Status > 300) { logErrorMessage(initiateMultipartUploadOutput.CommonMsg); return; } const uploadId = initiateMultipartUploadOutput.InterfaceResult.UploadId; const parts: Part[] = []; // 上传段 const uploadPartOutput = await obsClient.uploadPart({ Bucket: bucketName, Key: objectName, UploadId: uploadId, PartNumber: 1, Body: "Hello OBS~" }); if (uploadPartOutput.CommonMsg.Status > 300) { logErrorMessage(uploadPartOutput.CommonMsg); return; } parts.push({ PartNumber: 1, ETag: uploadPartOutput.InterfaceResult.ETag, }); // 合并段 const completeMultipartUploadOutput = await obsClient.completeMultipartUpload({ Bucket: bucketName, Key: objectName, UploadId: uploadId, Parts: parts }); if (completeMultipartUploadOutput.CommonMsg.Status > 300) { logErrorMessage(uploadPartOutput.CommonMsg); return; } console.log("uploadFile successful!!"); console.log("RequestId: %s", completeMultipartUploadOutput.CommonMsg.RequestId); console.log("ETag:%s", completeMultipartUploadOutput.InterfaceResult.ETag); } catch(error) { console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network."); console.log(error); } } function logErrorMessage(commonMsg: ICommonMsg) { console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response."); console.log("Status: %d", commonMsg.Status); console.log("Code: %s", commonMsg.Code); console.log("Message: %s", commonMsg.Message); console.log("RequestId: %s", commonMsg.RequestId); } |
其他分段操作请参考:
父主题: 多段相关接口(Harmony SDK)