You need to enable JavaScript to run this app.
导航
上传回调(Harmony SDK)
最近更新时间:2024.12.23 17:29:49首次发布时间:2024.12.23 17:29:49

上传回调是指客户端在请求时携带回调(Callback)参数,服务端在上传完成后,发送同步的 POST 回调请求到 CallBack 中指定的第三方应用服务器,在服务器确认接受并返回结果后,才将所有结果返回给客户端。

示例代码

普通上传实现上传回调

import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk';

// 创建客户端
const client = new TosClient({
  accessKeyId: "Provide your ak", 
  accessKeySecret: "Provide your sk", 
  securityToken: 'Provide your securityToken',
  region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。
  endpoint: "Provide your endpoint", // 填写域名地址
});

function handleError(error: Error) {
  if (error instanceof TosClientError) {
    console.log('Client Err Msg:', error.message);
    console.log('Client Err Stack:', error.stack);
  } else if (error instanceof TosServerError) {
    console.log('Request ID:', error.requestId);
    console.log('Response Status Code:', error.statusCode);
    console.log('Response Header:', error.headers);
    console.log('Response Err Code:', error.code);
    console.log('Response Err Msg:', error.message);
  } else {
    console.log('unexpected exception, message: ', error);
  }
}

async function main() {
  try {
    const callbackUrl = '*** Provide your callback url ***';
    const objectKey = '*** Provide your object key ***';

    // 设置上传回调参数
    // 可以根据需求设置 callback 参数
    const callback = `
    {
      "callbackUrl" : "${callbackUrl}", 
      "callbackBody" : ${'"{\\"bucket\\": ${bucket}, \\"object\\": ${object}, \\"key1\\": ${x:key1}}"'}, 
      "callbackBodyType" : "application/json"                
    }`;  // callback 的值需要进行 base64 编码
    // 配置相关变量参数
    const callbackVar = `
    {
      "x:key1" : "ceshi"
    }`;// callbackVar 的值需要进行 base64 编码
    const res = await client.putObject({
      Bucket: bucketName,
      Key: objectKey,
      Content: buffer.from('object content').buffer,
      Callback: buffer.from(callback).toString('base64'),
      CallbackVar: buffer.from(callbackVar).toString('base64'),
    });
    console.log('putObject CallbackResult: ', res.CallbackResult);
  } catch (error) {
    handleError(error);
  }
}

main();

分片上传实现上传回调

import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk';

// 创建客户端
const client = new TosClient({
  accessKeyId: "Provide your ak", 
  accessKeySecret: "Provide your sk", 
  securityToken: 'Provide your securityToken',
  region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。
  endpoint: "Provide your endpoint", // 填写域名地址
});

function handleError(error: Error) {
  if (error instanceof TosClientError) {
    console.log('Client Err Msg:', error.message);
    console.log('Client Err Stack:', error.stack);
  } else if (error instanceof TosServerError) {
    console.log('Request ID:', error.requestId);
    console.log('Response Status Code:', error.statusCode);
    console.log('Response Header:', error.headers);
    console.log('Response Err Code:', error.code);
    console.log('Response Err Msg:', error.message);
  } else {
    console.log('unexpected exception, message: ', error);
  }
}

async function main() {
  try {
    const callbackUrl = '*** Provide your callback url ***';
    const callback = `
    {
      "callbackUrl" : "${callbackUrl}",
      "callbackBody" : ${'"{\\"bucket\\": ${bucket}, \\"object\\": ${object}, \\"key1\\": ${x:key1}}"'},
      "callbackBodyType" : "application/json"
    }`;  // callback 的值需要进行 base64 编码
    // 配置相关变量参数
    const callbackVar = `
    {
      "x:key1" : "ceshi"
    }`;// callbackVar 的值需要进行 base64 编码
    const bucketName = 'harmony-sdk-test-bucket';
    const objectName = 'example_dir/multipartExample';
    // 本地 example_dir 文件夹下的 multipartExample 文件
    const filePath = './example_dir/multipartExample';
    // 初始化分片,指定对象权限为私有,存储类型为低频并设置元数据信息
    const res = await client.createMultipartUpload({
      Bucket: bucketName,
      Key: objectName,
      ACL: ACLType.ACLPrivate,
      StorageClass: StorageClassType.StorageClassIa,
    });
    console.log('CreateMultipartUploadV2 Upload ID:', res.UploadId);

    // 获取本地文件信息并准备进行分片
    const stats = await fs.statSync(filePath);
    // 文件总大小
    const totalSize = stats.size;
    // part size 大小设置为 5M
    const partSize = 5 * 1024 * 1024;
    let offset = 0;
    // partNumber 编号从 1 开始
    let partNumber = 1;
    const partsInfo: UploadedPart[] = [];
    while (offset < totalSize) {
      const uploadResult = await client.uploadPart({
        Bucket: bucketName,
        Key: objectName,
        PartNumber: partNumber,
        UploadID: res.UploadId,
        Content: fs.createReadStream(filePath, {
          start: offset,
          end: offset + partSize - 1,
        }),
      });
      const eTag = uploadResult.ETag;
      console.log(`partNumber${partNumber} Etag:`, eTag);
      partsInfo.push(new UploadedPart(partNumber, eTag));
      partNumber++;
      offset += partSize;
    }
    console.log('parts information', partsInfo);

    // 完成分片上传
    const completeRes = await client.completeMultipartUpload({
      Bucket: bucketName,
      Key: objectName,
      UploadID: res.UploadId,
      Parts: partsInfo,
      Callback: buffer.from(callback).toString('base64'),
      CallbackVar: buffer.from(callbackVar).toString('base64'),
    });

    console.log('result callback result:', completeRes.CallbackResult);
  } catch (error) {
    handleError(error);
  }
}

main();

相关文档

关于上传回调的详细介绍,请参见上传回调