上传指定文件至云侧
=========

开发者可以快速将本地设备上的文件上传至云侧，上传完后，可以前往AppGallery Connect的“云存储”页面，查看上传的文档内容。

#### 约束与限制

支持Phone、Tablet设备。并且从5.1.0(18)版本开始，新增支持Wearable设备；从5.1.1(19)版本开始，新增支持TV设备；从6.1.0(23)版本开始，新增支持PC/2in1设备。

#### 前提条件

已[初始化存储实例](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cloudfoundation-storage-initialize-bucket)。

#### 操作步骤

1.  选择待上传的文件，下方示例代码中使用[photoAccessHelper.PhotoViewPicker](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-photoaccesshelper-photoviewpicker)指定需要上传的文件。
    
2.  将待上传的文件复制到[context.cacheDir](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-application-context#属性)目录下。
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/bc/v3/s9T7snYTQY621WSQJRub7w/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073603Z&HW-CC-Expire=86400&HW-CC-Sign=6ED1A2461C4177A62E12ACFD5FAA679E3B6F836F025C79B20C9ADC1CA6392A42)
    
    由于StorageBucket.uploadFile接口传入参数localPath只能设置为context.cacheDir目录下的文件路径，所以上传前需要先将文件复制到context.cacheDir目录下。
    
3.  调用[StorageBucket.uploadFile](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/cloudfoundation-cloudstorage#uploadfile)接口创建上传任务，监听上传任务的progress、completed、failed等事件。
    
4.  启动上传任务。
    

完整的示例代码如下：

import { cloudStorage } from '@kit.CloudFoundationKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { GlobalContext } from '../common/GlobalContext';

let storageBucket: cloudStorage.StorageBucket = cloudStorage.bucket();

@Component
export struct testPage {
  build() {
  }

  // 上传指定文件至云侧
  upload() {
    this.selectPhoto().then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
      let fileUri = photoSelectResult.photoUris\[0\];
      hilog.info(0x0000, 'testTag', \`pick file ${fileUri}\`);
      let fileName = fileUri.split('/').pop() as string;
      hilog.info(0x0000, 'testTag', \`file name ${fileName}\`);
      let cacheFile = GlobalContext.getContext().cacheDir + '/' + fileName;
      hilog.info(0x0000, 'testTag', \`cacheFile ${cacheFile}\`);
      // 将选中文件copy至cache目录下
      this.copyFile(fileUri, cacheFile);
      // 上传至云存储默认实例
      this.uploadFile(cacheFile, \`screenshot/${fileName}\`);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', \`Failed to upload file, code: ${err.code}, message: ${err.message}\`);
    })
  }

  /\*\*
   \* @throws photoViewPicker select throws
   \*/
  selectPhoto(): Promise<photoAccessHelper.PhotoSelectResult> {
    // 使用photoAccessHelper选择指定的文件
    let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE\_TYPE; // 过滤选择媒体文件类型为IMAGE
    photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
    let photoViewPicker = new photoAccessHelper.PhotoViewPicker();
    return photoViewPicker.select(photoSelectOptions);
  }

  copyFile(srcPath: string, dstPath: string) {
    try {
      let srcFile = fileIo.openSync(srcPath);
      let dstFile = fileIo.openSync(dstPath, fileIo.OpenMode.READ\_WRITE | fileIo.OpenMode.CREATE);
      fileIo.copyFileSync(srcFile.fd, dstFile.fd);
      fileIo.closeSync(srcFile);
      fileIo.closeSync(dstFile);
    } catch (e) {
      hilog.error(0x0000, 'testTag', \`copy file failed ${e.message}\`);
      return;
    }
  }

  uploadFile(localPath: string, cloudPath: string) {
    storageBucket.uploadFile(GlobalContext.getContext(), {
      localPath: localPath, // 本地文件路径（context.cacheDir目录下的文件路径）
      cloudPath: cloudPath   // 云侧路径，支持传入“文件目录/文件名”（如“screenshot/demo.jpg”），或仅传入文件名。
    }).then((task: request.agent.Task) => {
      task.on('progress', (progress) => {
        hilog.info(0x0000, 'testTag', \`on progress ${JSON.stringify(progress)}\`);
      });
      task.on('completed', (progress) => {
        hilog.info(0x0000, 'testTag', \`on completed ${JSON.stringify(progress)}\`);
        // 删除cache目录临时文件
        fileIo.unlink(localPath).catch((err: BusinessError) => {
          hilog.error(0x0000, 'testTag', \`Failed to unlink, code: ${err.code}, message: ${err.message}.\`);
        });
      });
      task.on('failed', (progress) => {
        hilog.info(0x0000, 'testTag', \`on failed ${JSON.stringify(progress)}\`);
        // 删除cache目录临时文件
        fileIo.unlink(localPath).catch((err: BusinessError) => {
          hilog.error(0x0000, 'testTag', \`Failed to unlink, code: ${err.code}, message: ${err.message}.\`);
        });
      });
      task.on('response', (response) => {
        hilog.info(0x0000, 'testTag', \`on response ${JSON.stringify(response)}\`);
      });

      // start task
      task.start((err: BusinessError) => {
        if (err) {
          hilog.error(0x0000, 'testTag',
            \`Failed to start a file upload task, code: ${err.code}, message: ${err.message}\`);
        } else {
          hilog.info(0x0000, 'testTag', \`Succeeded in starting a file upload task.\`);
        }
      });
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', \`Failed to upload file, code: ${err.code}, message: ${err.message}\`);
    })
  }
}

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/91/v3/Nhr-xmg4RR6KigObGoOJfw/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073603Z&HW-CC-Expire=86400&HW-CC-Sign=1ACA03115F19057ED30A9183157D781D9A597D298F0EA836526ADFF5AC1F86DE)

上传完成，可以登录[AppGallery Connect](https://developer.huawei.com/consumer/cn/service/josp/agc/index.html)，选择项目，进入“云存储”界面查看文件列表。