目录

快应用Serverless开发

简介

[h2]主要功能

云函数

云函数提供FaaS(Function as a Service)能力,开发者无需自建服务器,只需聚焦业务逻辑、开发并上传函数代码,即可构建高可用、可伸缩的Serverless应用。使用云函数可以帮助开发者大幅简化应用开发与传统运维相关的事务,降低应用功能的实现门槛,快速构建业务能力。

云数据库

云数据库提供托管在云端的数据存储服务,采用基于对象模型的数据存储结构,支持单个或批量操作对象,如新增、修改、删除和查询等丰富的API接口。

云存储

云存储是专为开发者打造的可伸缩、免维护的云端存储服务,开发者可以用于存储图片、音频、视频或其他由用户生成的内容。

认证服务

大部分的应用都需要对用户的业务访问进行身份认证,以便为用户提供个性化体验。但是端到端完整构建一套用户认证系统会面临很多挑战。认证服务可以为您的应用快速构建安全可靠的用户认证系统,您只需在应用中访问认证服务的相关能力,而不需要关心云侧的设施和实现。

认证服务为云函数、云数据库、云存储等服务提供了全面且自适应的安全支撑,可令您对用户数据的保护事半功倍。

[h2]优势

准入条件

在进行快应用Serverless开发前,请先完成如下准备工作:

新建Serverless项目

  1. 打开华为快应用IDE,菜单选择“新建项目 > 快应用”,设备选择“手机/平板”,点击“下一步”。

  2. 选择“云开发模板(beta)”页签,点击“登录”在跳转的网页中登录注册的华为开发者账号。

  3. 登录成功后,选择模板后,点击“下一步”。

  4. 选择关联应用、模板,设置项目路径后,点击“确定”。

    【关联应用】

    • 团队:在HarmonyOS 开发者中心上创建快应用使用账号归属的团队。
    • 项目:已创建快应用所属的项目。
    • 应用:已创建的快应用。
    • 项目路径:存放Serverless项目的路径。

    如果选择项目后,提示未开通云服务,则选择开通所需接入的服务。

    如果提示还有未开通的服务,可以点击“是”跳过开通服务的步骤,先创建项目。

新建项目结构主要由quickapp.config.json、client、cloudfunctions组成。

|—— client 用于存放标准快应用代码

|—— |—— src 标准快应用源码目录

|—— —— |—— Common 快应用公共资源文件目录

|—— —— |—— Hello 快应用主文件目录

|—— —— |—— app.ux 快应用入口文件

|—— —— |—— manifest.json 快应用配置文件

|—— |—— package.json 快应用代码依赖云函数SDK的配置文件

|—— cloudfunctions 云函数目录,该目录下可以创建多个云函数目录

|—— quickapp.config.json serverless项目的配置文件

quickapp.config.json针对serverless项目的配置信息如下:

集成SDK

  1. 确保已开通所有需要接入的服务。
  2. 找到工程client目录下的“agconnect-services.json”文件,右键鼠标选择“更新agconnect-services.json文件”。

  3. 打开package.json文件,编辑dependencies区域需要集成服务SDK的版本。

    服务

    SDK名称

    版本

    认证服务

    @agconnect/auth

    最新版本请参见认证服务的“SDK版本更新说明”。

    云函数

    @agconnect/function

    最新版本请参见云函数的“SDK版本更新说明”。

    云存储

    @agconnect/cloudstorage

    最新版本请参见云存储的“SDK版本更新说明”。

    云数据库

    @agconnect/database

    最新版本请参见云数据库的“SDK版本更新说明”。

    以下代码以SDK版本为1.2.0为例,实际请替换为需要集成的版本号。

    "dependencies": {
      "@agconnect/auth": "1.2.0",
      "@agconnect/function": "1.2.0"
      "@agconnect/cloudstorage": "1.2.0"
      "@agconnect/database": "1.2.0"
    }
  4. 选择快应用IDE的“终端”页签,执行如下命令进入client目录安装SDK。
    cd client
    npm install

    安装完成后,在左侧导航目录将生成node_modules目录。

  5. 如果接入云数据库服务,需要在工程的node_modules/protobufjs/src/util目录下的minimal.js文件中的util.global变量增加|| global。
    util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self   !== "undefined" && self  || this || global; // eslint-disable-line no-invalid-this

开发快应用功能

打开工程目录中相应的工程文件,参考快应用规范进行代码的编辑。

快应用规范包括:

接入云函数服务

[h2]接入流程

[h2]开通云函数服务

请先开通云函数服务。如果已开通,则跳过本步骤。

[h2]同步云函数列表

在进行云函数开发前,需进行同步云函数操作,以便将在HarmonyOS 开发者中心配置的云端云函数列表同步到IDE。

选择云函数主目录cloudfunctions,右击鼠标选择“同步云函数列表”。

同步完成后,在项目导航树的cloudfunctions目录下生成以云函数名命名的文件夹。

此操作不会下载云函数代码。

[h2]下载云函数

选中同步下来的云函数目录,右击鼠标选中“下载云函数代码”。

同步下来的每个云函数目录都需要执行。

[h2]管理云函数

创建云函数

  1. 选择云函数主目录cloudfunctions,右击鼠标选择“新建nodejs云函数”。
  2. 选中新建的云函数,右击鼠标选择“上传云函数”,点击“确定”。
    • 函数名:名称不超过32位,支持小写字母、数字和中划线(-),以小写字母开头,小写字母和数字结尾。
    • CPU:函数容器所占有的CPU大小,CPU单位为千分。
    • 内存:函数容器所占有的内存大小,大小为M。
    • 运行环境:函数容器的运行环境,当前仅支持nodejs。
    • 函数入口:包括入口文件相对根目录路径和入口函数名称,通过"."连接,例如handler.myHandler,其中handler为入口文件名称,在根目录下,myHandler为函数名。
    • 环境变量:可将用户需要的变量配置信息通过环境变量传入到函数执行环境中,用于函数运行时读取。

  3. 打开创建的js文件编辑函数,相关语法请参见“Node.js”。
  4. 如果云函数中需要引入第三方的依赖,可以在该云函数目录下,执行npm命令下载并引用第三方依赖,上传云函数时会将该云函数整个目录打包成函数部署包上传。

    如下图所示,在终端页签进入云函数目录,执行npm命令下载依赖后,在云函数目录下的package.json文件中增加依赖配置信息,在云函数的node_modules目录下生成以第三方依赖命名的目录。

  5. 选择创建的函数,右击鼠标选择“上传云函数”,将函数同步上传至云端。

修改云函数

  1. 在云函数主目录cloudfunctions下,点击待修改云函数文件夹下的js文件。
  2. 如果云函数中需要引入第三方的依赖,可以在该云函数目录下,执行npm命令下载并引用第三方依赖,上传云函数时会将该云函数整个目录打包成函数部署包上传。

    如下图所示,在终端页签进入云函数目录,执行npm命令下载依赖后,在云函数目录下的package.json文件中增加依赖配置信息,在云函数的node_modules目录下生成以第三方依赖命名的目录。

    函数部署包需要使用如下结构,处理程序所在代码文件必须在zip根目录下,依赖项放到这node_modules目录下。

    my-function.zip

    |—— index.js

    |—— node_modules

    |—— async

    |—— async-listener

  3. 修改完代码后,选中新建的云函数,右击鼠标选择“上传云函数”。
  4. 确认云函数信息后,点击“确定”。

删除云函数

  1. 选中待删除的云函数目录,右击鼠标选择“删除云函数”。
  2. 在弹出框中点击“删除”,则将IDE本地和云端的云函数同步删除。

    删除函数会将函数的所有版本、别名数据删除,函数删除后数据不可恢复。

[h2]测试云函数

测试前,请确保连接的手机可正常访问网络。

  1. 选中需要测试的云函数目录,右击鼠标选择“测试云函数”。
  2. 将在云端执行测试后,返回测试结果。

[h2]管理版本

$latest版本

首次创建函数,版本默认为$latest。

开发者只能基于$latest版本修改并发布版本,发布的版本不支持修改,只支持查看和删除。发布后展示的版本号从1开始递增。

例如,首次创建后版本为$latest,将$latest版本发布为版本1。一段时间后需要为函数增加新的功能,可以在$latest版本中修改,并将修改后的版本发布为版本2。开发者可以调用版本1和版本2的函数实现不同的功能。

发布版本

将测试通过的云函数发布为正式版本,每个云函数可以发布多个版本。

  1. 选中待发布的云函数目录,右击鼠标选择“发布新版本”。
  2. 填写新版本的描述信息,点击“发布”,则将发布此函数的新版本至云端。

删除版本

  1. 选中待删除版本的云函数目录,右击鼠标选择“管理版本”。
  2. 点击版本所在行的删除图标,删除版本。

[h2]管理别名

创建别名

通过创建别名,可以将云函数和指定发布的版本关联起来。

  1. 选中待创建别名的云函数目录,右击鼠标选择“创建别名”。
  2. 填写别名信息后,点击“创建”。
    • 别名:必须唯一。别名名称不超过16位,支持小写字母、数字和中划线(-),以小写字母开头,小写字母和数字结尾。
    • 描述:别名的描述。
    • 版本:别名指向的版本。
    • 其他版本:别名支持两个版本间的灰度能力,通过权重配置,将别名上的流量按比例指向不同版本。

修改、删除别名

  1. 选中待修改别名的云函数目录,右击鼠标选择“管理别名”。
  2. 点击别名所在行的删除图标 ,删除别名。点击编辑图标 ,修改别名信息。

[h2]管理触发器

创建HTTP触发器

  • 在应用中使用云函数SDK的API调用云函数,需创建HTTP类型的触发器。强烈建议为调用云函数的别名创建HTTP类型触发器。
  • 云函数每个版本、每个别名只能创建一个HTTP类型的触发器。

为云函数的别名创建HTTP触发器的步骤如下。

  1. 选中待创建触发器的云函数目录,右击鼠标选择“创建触发器”。

  2. 填写触发器信息后,点击“添加”。
    • 别名/版本:选择需要创建触发器的云函数别名或者版本。
    • 触发器类型:选择“HTTP”。
    • 请求方式:目前仅支持POST请求方式。
    • 认证类型:选择“API客户端鉴权(Client适用)”,表示端侧网关认证,适用于来自APP客户端侧的函数调用。

创建CRON触发器

在指定时间点定时触发云函数时,需创建CRON类型触发器。

  1. 打开快应用IDE,选中待创建触发器的云函数目录,右击鼠标选择“创建触发器”。
  2. 填写触发器信息后,点击“添加”。
    • 别名/版本:选择需要创建触发器的云函数别名或者版本。
    • 触发器类型:选择“CRON”。
    • 事件值:调用函数时传入的事件内容,格式为JSON字符串。
    • 日程表:触发函数调用的时间点,设置方式见下表。

    格式

    说明

    以“@every ValueUnit”格式

    Value为一个正整数,Unit可以为“s”、“m”、“h”,表示每隔ValueUnit的时间触发一次函数。例如,“@every 6m” 表示每隔6分钟触发一次函数。

    通过kubernetes cronjob支持的标准的cron表达式的形式(Minutes Hours Day-of-month Month Day-of-week )设置

    • Minutes:值范围0-59,支持括号内的特殊字符(, - * /)
    • Hours:值范围0-23,支持括号内的特殊字符(, - * /)
    • Day-of-month:值范围1-31,支持括号内的特殊字符(, - * /)
    • Month:值范围1-12或JAN-DEC,支持括号内的特殊字符(, - * /)
    • Day-of-week:值范围1-7或SUN-SAT,支持括号内的特殊字符(, - * )
    说明:

    cron以UTC时间运行,即北京时间减去8个小时。

    常用设置示例如下:

    • 如希望北京时间每天12:00触发函数,则UTC时间为每天4:00触发函数,cron表达式设为:0 4 * * *
    • 如希望北京时间每天12:30触发函数,则UTC时间为每天4:30触发函数,cron表达式设为:30 4 * * *
    • 如希望北京时间每小时的26分,29分,33分触发函数,则UTC时间为每小时的26分,29分,33分触发函数,cron表达式设为:26,29,33 * * * *
    • 如希望北京时间周一到周五的每天12:30触发函数,则UTC时间为周一到周五的每天4:30触发函数,cron表达式设为:30 4 * * MON-FRI
    • 如希望北京时间周一到周五的每天12:00-14:00每5分钟触发函数,则UTC时间为周一到周五的每天4:00-6:00每5分钟触发函数,cron表达式设为:0/5 4-6 * * MON-FRI
    • 如希望北京时间一到四月每天12:00触发函数,则UTC时间为一到四月每天4:00触发函数,cron表达式设为:0 4 * JAN,FEB,MAR,APR *
    • 调用方式:支持同步调用和异步调用。

[h2]查询触发器标识

  1. 选中待查询的云函数目录,右击鼠标选择“管理触发器”。
  2. 选择待查询云函数的别名或者版本,复制触发器的“触发Url”信息。

    “触发URL”的后缀即为触发器的标识,格式为“函数名-函数别名”。

    例如触发Url为:/functions/6OPR7HWgZU1F1K4jtsM25s/function2-function2alias,“fuction1-function1alias”即为针对云函数别名的HTTP触发器标识。

[h2]调用云函数

调用云函数分触发器调用和应用客户端调用两种方式。

  1. 在调用云函数的ux文件中导入agc组件。
    import agconnect from '@agconnect/api';
    import '@agconnect/function';
    import "@agconnect/instance";
  2. 初始化AGC SDK。
    let agConnectConfig = require('./agconnect-services.json');
    agconnect.instance().configInstance(agConnectConfig);
  3. 在函数或函数别名中创建一个HTTP类型的触发器,详细参见“创建HTTP触发器”。
  4. 调用wrap方法设置函数,在方法中传入调用云函数的别名对应的HTTP触发器标识,返回得到可执行云函数的对象。

    调用云函数时,强烈建议通过云函数别名进行调用。这样当云函数变动升级后,只需修改别名中指定的版本即可。

    let functionCallable = agconnect.function().wrap("functionname-functionalias");//functionname-functionalias为云函数别名对应的HTTP触发器标识

  5. (可选)可修改全局网络连接超时时长,详见config.network说明说明,但不支持通过设置timeout属性设置超时时长。
  6. 调用call方法运行云函数。如果函数有入参,可以将参数转化为JSON对象或JSON字符串传入,如果没有参数则不传。

    let reqBody = {"data":"value"};

    let functionResult = await functionCallable.call(reqBody);

  7. 如果您需要关注函数的返回值,可调用getValue方法获取。

    let returnValue = functionResult.getValue();

    更多接口请参见“云函数API”。

接入认证服务

确保开通认证服务,并集成对应的SDK。

接入认证服务提供的账号相关功能:

更多接口请参见“认证服务API”。

接入云存储服务

  1. 完成认证服务匿名登录功能的接入,具体请参考接入认证服务。
  2. 确保开通认证服务,并集成对应的SDK。
  3. 检查agconnect-services.json文件中"service -> cloudstorage"标签是否已默认配置default_storage。当未配置时,SDK初始化存储会失败,请手工配置default_storage的值。查询default_storage的值方法如下:
    1. 登录HarmonyOS 开发者中心,进入“应用管理”页面。
    2. 左上角筛选接入云存储服务的快应用。
    3. 左侧导航栏选择“开发能力配置 > 云存储”,界面上存储示例即default_storage所需配置的值。

    "cloudstorage":{  
        "default_storage":"storagetest1-10do4-skqea",  
        "storage_url":"https://agc-storage-drcn.platform.dbankcloud.cn"  
    }
  4. 初始化AGC。
    let agConnectConfig = require('./agconnect-services.json');
    agconnect.instance().configInstance(agConnectConfig);
  5. 初始化云存储。
    const storageManagement = agconnect.cloudStorage();
  6. 创建引用。
  7. 进行文件管理,包括上传文件、删除文件、文件元数据管理及获取文件的下载地址等功能。

更多接口介绍请参见“云存储API”。

接入云数据库服务

  1. 确保开通认证服务,并集成对应的SDK。
  2. 在需要使用云数据库服务的页面ux文档中添加对agconnect-services.json文件引用。以在hello.ux文件中引用为例。
    const context = require('../agconnect-services.json');
  3. 在HarmonyOS 开发者中心上新增和导出对象类型。
  4. 在云侧新增数据存储区。
  5. 添加对象类型文件。
  6. 初始化云数据库。
  7. 写入数据。
  8. 查看数据。

更多接口介绍请参见“云数据库API”。

Demo

[h2]云函数

查看视频教程

<template>
  <!-- Only one root node is allowed in template. -->
  <div class="container">
    <input type="number" style="border: 1px solid #000000;font-size: 35px" placeholder="Enter year to determine whether it is a leap year" onenterkeyclick="callFunction" onchange="change" />
    <text class="title" style="margin-top: 20px;font-size: 35px">result:{{this.result}}</text>
  </div>
</template>
<style>
  .container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>
<script>
  module.exports = {
    data: {
      componentData: {},
      result: "",
      dateValue: ""
    },
    onInit() {
      this.$page.setTitleBar({
        text: "menu",
        textColor: "#ffffff",
        backgroundColor: "#007DFF",
        backgroundOpacity: 0.5,
        menu: true
      });
    },
    change: function (e) {
      this.dateValue = e.value;
    },
    callFunction() {
      console.log("Enter Date:" + this.dateValue);
      let agconnect = this.$app.$def.agc;
      let bodyParam = { year: this.dateValue };
      let functionCallable = agconnect.function().wrap("fun2-fun2alais");
      functionCallable.call(bodyParam).then(res => {
        console.log(res.getValue());
        this.result = res.getValue().result;
      });
    }
  };
</script>

[h2]认证

查看视频教程

<template>
    <div class="container">
        <div class="label-item">
            <label class="lable1" target="input1">Account:</label>
            <input class="flex" id="input1" placeholder="Please enter your account." onchange="setAcount" />
        </div>
        <div class="item-container">
            <label class="lable1" target="select1">Account Type:</label>
            <select class="select" id="select1" onchange="changeAccountType">
                <option class="option" value="phone" selected="true">phone</option>
                <option class="optionrgb" value="email">email</option>
            </select>
        </div>
        <div show="{{this.loginmode==='password'}}" class="label-item">
            <label class="lable1" target="input2">Password:</label>
            <input class="flex" id="input2" placeholder="Please enter your password." onchange="setPassword" />
        </div>
        <div show="{{this.loginmode==='verifycode'}}" class="label-item">
            <label class="lable1" target="input3">Verify Code:</label>
            <input class="flex" id="input3" placeholder="Please enter verify code." style="width: 350px" onchange="setVerifyCode" />
            <input show="{{this.codeInterval<=0}}" type="button" class="button" style="width: 160px" value="Get Code" @click="getVerifyCode" />
            <text show="{{this.codeInterval>0}}" style="width: 100px;height:70px;margin-top:35px;margin-left: 15px">Waiting {{this.codeInterval}}s</text>
        </div>
        <div class="item-container">
            <label class="lable1" target="select1">Login Mode:</label>
            <select class="select" id="select1" onchange="changeLoginMode">
                <option class="option" value="verifycode" selected="true">verifycode</option>
                <option class="optionrgb" value="password">password</option>
            </select>
        </div>
        <div class="label-item">
            <input show="{{this.loginmode==='password'}}" type="button" class="button" value="Login by PWD" style="width: 90%;margin-left:40px;" @click="signPassword" />
            <input show="{{this.loginmode==='verifycode'}}" type="button" class="button" value="Login by Code" style="width: 90%;margin-left:40px;" @click="signVerifycode" />
        </div>
        <div class="label-item">
            <input type="button" class="button" value="User Register" @click="registerUser" />
            <input type="button" class="button" value="User Deregister" style="margin-left: 100px" @click="deregisterUser" />
        </div>
        <div class="label-item">
            <input type="button" class="button" value="Get UserInfo" @click="getCurrentUser" />
            <input type="button" class="button" value="Log Out" style="margin-left: 100px" @click="signout" />
        </div>
        <div class="label-item">
            <label target="input1">isAnoymous:</label>
            <input class="flex1" id="input4" placeholder="{{isAnoymous}}" />
        </div>
        <div class="label-item">
            <label target="input1">uid:</label>
            <input class="flex1" id="input5" placeholder="{{uid}}" />
        </div>
        <div class="label-item">
            <label target="input1">Email:</label>
            <input class="flex1" id="input6" placeholder="{{email}}" />
        </div>
        <div class="label-item">
            <label target="input1">phone:</label>
            <input class="flex1" id="input7" placeholder="{{phone}}" />
        </div>
        <div class="label-item">
            <label target="input1">providerId:</label>
            <input class="flex1" id="input10" placeholder="{{providerId}}" />
        </div>
        <div class="label-item">
            <label target="input1">accessToken:</label>
        </div>
        <div class="label-item">
            <textarea placeholder="{{accessToken}}"></textarea>
        </div>
    </div>
</template>
<style>
    @import "../Common/CSS/common.css";
    .container {
        /* flex-direction: row; */
        /* justify-content: center; */
        /* align-content: center; */
        /* align-items: center; */
    }
    input {
        width: 350px;
        height: 70px;
        background-color: #ffffff;
        border: 1px solid;
        margin-top: 35px;
        align-content: center;
    }
    .label-item {
        align-items: center;
        border-bottom-width: 1px;
        border-color: #ffffff;
    }
    label {
        font-size: 35px;
        width: 250px;
        height: 70px;
    }
    .title {
        font-size: 100px;
    }
    .select {
        margin-top: 10px;
        margin-right: 30px;
        align-items: flex-start;
        border-color: #007DFF;
        border-width: 1px;
        width: 220px;
        height: 70px;
    }
    .lable1 {
        width: 250px;
    }
    .flex {
        width: 500px;
    }
    .flex:focus {
        background-color: #dcdcdc;
    }
    .flex1 {
        width: 400px;
        margin-left: 10px;
    }
    .button:active {
        background-color: #dcdcdc;
    }
</style>
<script>
    import prompt from "@system.prompt";
    module.exports = {
        data: {
            acount: "",
            password: "",
            verifyCode: "",
            loginmode: "verifycode",
            accounttype: "phone",
            isAnoymous: "",
            uid: "",
            email: "",
            phone: "",
            providerId: "",
            accessToken: "",
            codeInterval: 0
        },
        onShow(options) {
            setInterval(() => {
                if (this.codeInterval > 0) {
                    this.codeInterval = this.codeInterval - 1;
                    console.log("codeInterval:" + this.codeInterval);
                }
            }, 1000);
        },
        changeLoginMode(e) {
            this.loginmode = e.newValue;
            prompt.showToast({
                message: `[${e.newValue}] selected`,
                duration: 4000,
                gravity: "center"
            });
        },
        changeAccountType(e) {
            this.accounttype = e.newValue;
            prompt.showToast({
                message: `[${e.newValue}] selected`,
                duration: 4000,
                gravity: "center"
            });
        },
        setAcount(e) {
            this.acount = e.value;
        },
        setPassword(e) {
            this.password = e.value;
        },
        setVerifyCode(e) {
            this.verifyCode = e.value;
        },
        getVerifyCode() {
            let accounttype = this.accounttype;
            let acount = this.acount;
            let agconnect = this.$app.$def.agc;
            if (accounttype === "phone") {
                agconnect.auth.PhoneAuthProvider.requestVerifyCode("86", acount, agconnect.auth.Action.ACTION_REGISTER_LOGIN, "zh_cn")
                    .then(res => {
                        console.log("CodePeriod:" + res.getValidityPeriod() + "; CodeInterval:" + res.getShortestInterval());
                        this.codeInterval = res.getShortestInterval();
                        prompt.showToast({
                            message: "getVerifyCode success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            } else if (accounttype === "email") {
                agconnect.auth.EmailAuthProvider.requestVerifyCode(acount, agconnect.auth.Action.ACTION_REGISTER_LOGIN, "zh_cn", 30)
                    .then(res => {
                        console.log("CodePeriod:" + res.getValidityPeriod() + "; CodeInterval:" + res.getShortestInterval());
                        this.codeInterval = res.getShortestInterval();
                        prompt.showToast({
                            message: "getVerifyCode success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            }
        },
        signVerifycode() {
            let acount = this.acount;
            let verifyCode = this.verifyCode;
            let password = this.password;
            let agconnect = this.$app.$def.agc;
            let accounttype = this.accounttype;
            if (accounttype === "phone") {
                let credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode("86", acount, password, verifyCode);
                agconnect
                    .auth()
                    .signIn(credential)
                    .then(res => {
                        this.getCurrentUser();
                        prompt.showToast({
                            message: "phone login success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            } else if (accounttype === "email") {
                let credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(acount, password, verifyCode);
                agconnect
                    .auth()
                    .signIn(credential)
                    .then(res => {
                        this.getCurrentUser();
                        prompt.showToast({
                            message: "email login success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            }
        },
        signPassword() {
            let acount = this.acount;
            let password = this.password;
            let agconnect = this.$app.$def.agc;
            let accounttype = this.accounttype;
            if (accounttype === "phone") {
                let credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword("86", acount, password);
                agconnect
                    .auth()
                    .signIn(credential)
                    .then(res => {
                        this.getCurrentUser();
                        prompt.showToast({
                            message: "login phone success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                        console.log(JSON.stringify(err));
                    });
            } else if (accounttype === "email") {
                let credential = agconnect.auth.EmailAuthProvider.credentialWithPassword(acount, password);
                agconnect
                    .auth()
                    .signIn(credential)
                    .then(res => {
                        this.getCurrentUser();
                        prompt.showToast({
                            message: "login email success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            }
        },
        registerUser() {
            let acount = this.acount;
            let verifyCode = this.verifyCode;
            let password = this.password;
            let agconnect = this.$app.$def.agc;
            let accounttype = this.accounttype;
            if (accounttype === "phone") {
                let phone = new agconnect.auth.PhoneUser("86", acount, password, verifyCode);
                agconnect
                    .auth()
                    .createPhoneUser(phone)
                    .then(res => {
                        this.getCurrentUser();
                        prompt.showToast({
                            message: "register phone success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            } else if (accounttype === "email") {
                let email = new agconnect.auth.EmailUser(acount, password, verifyCode);
                agconnect
                    .auth()
                    .createEmailUser(email)
                    .then(res => {
                        this.getCurrentUser();
                        prompt.showToast({
                            message: "register email success",
                            duration: 4000,
                            gravity: "center"
                        });
                    })
                    .catch(err => {
                        prompt.showToast({
                            message: JSON.stringify(err),
                            duration: 4000,
                            gravity: "center"
                        });
                    });
            }
        },
        getCurrentUser() {
            let agconnect = this.$app.$def.agc;
            agconnect
                .auth()
                .getCurrentUser()
                .then(res => {
                    if (res) {
                        this.isAnoymous = res.isAnonymous();
                        this.uid = res.getUid();
                        this.email = res.getEmail();
                        this.phone = res.getPhone();
                        this.providerId = res.getProviderId();
                        this.accessToken = res.getAccessToken();
                    } else {
                        this.isAnoymous = "";
                        this.uid = "";
                        this.email = "";
                        this.phone = "";
                        this.providerId = "";
                        this.accessToken = "";
                    }
                });
        },
        deregisterUser() {
            let agconnect = this.$app.$def.agc;
            agconnect
                .auth()
                .getCurrentUser()
                .then(async user => {
                    if (user) {
                        agconnect
                            .auth()
                            .deleteUser()
                            .then(() => {
                                this.getCurrentUser();
                                prompt.showToast({
                                    message: "deleteUser success",
                                    duration: 4000,
                                    gravity: "center"
                                });
                            })
                            .catch(err => {
                                prompt.showToast({
                                    message: JSON.stringify(err),
                                    duration: 4000,
                                    gravity: "center"
                                });
                            });
                    } else {
                        prompt.showToast({
                            message: "please login before",
                            duration: 4000,
                            gravity: "center"
                        });
                    }
                });
        },
        signout() {
            let agconnect = this.$app.$def.agc;
            agconnect
                .auth()
                .signOut()
                .then(res => {
                    this.getCurrentUser();
                    console.log("signOut success");
                    prompt.showToast({
                        message: "signOut success",
                        duration: 4000,
                        gravity: "center"
                    });
                })
                .catch(err => {
                    console.log(JSON.stringify(err));
                    prompt.showToast({
                        message: JSON.stringify(err),
                        duration: 4000,
                        gravity: "center"
                    });
                });
        }
    };
</script>

[h2]云存储

查看视频教程

index.ux

<template>
  <div class="container">
    <div style="height: 100px;margin-right: 6px;" class="label-item">
      <input class="greenButton" type="button" value="back" @click="back" />
      <input class="greenButton" type="button" value="list" @click="getList" />
      <input class="greenButton" type="button" value="listAll" @click="getListAll" />
      <input class="buleButton" type="button" value="putString" @click="putString" />
      <input class="buleButton" type="button" value="putFile" @click="putFile" />
    </div>
    <div style="height: 100px;margin-right: 6px;" class="label-item">
      <input class="greenButton" type="button" value="getMeta" @click="getMetaData" />
      <input class="greenButton" type="button" value="setMeta" @click="uploadMetaData" />
      <input class="greenButton" type="button" value="getURL" @click="getDownloadURL" />
      <input class="redButton" type="button" value="delete" @click="delete" />
    </div>
    <div style="margin: 5px;" class="label-item">
      <label style="width:500px;">result(display {{total}} records):</label>
    </div>
    <text style="text-align: center;margin-bottom: -20px;">{{progress}}%</text>
    <progress class="progress" style="color:#09ba07;stroke-width:10px;" percent="{{progress}}"></progress>
    <list style="margin-left: 5px;margin-right: 5px;height: 60px;" for="{{list}}">
      <list-item id="{{$item.path}}" class="{{selected==$item.path?'currentListItem':'listItem'}}" type="listItem" onclick="textClick" onlongpress="longpress">
        <image id="{{$item.path}}" src="{{$item.path.endsWith('/')?'../Common/folder.jpg':'../Common/file.jpg'}}" style="height:40px;margin:10px;"></image>
        <text id="{{$item.path}}" class="title">
          {{$item.path.length > 42 ? '...' +
          $item.path.substring($item.path.length - 42, $item.path.length) : $item.path}}
        </text>
      </list-item>
    </list>
    <image src="../Common/copy.jpg" style="height:30px;margin-left:20px;margin-top:10px;" onclick="copyClick"></image>
    <div class="label-item" style="padding-left: 5px;margin-left: 3px;margin-right: 5px;margin-top:5px;border: 1px solid #000000;">
      <textarea style="font-size: 30px;" disabled="true" placeholder="{{result}}"></textarea>
    </div>
    <div style="height: 80px;" class="label-item">
      <label style="margin-right: 5px;width:200px;height: 60px;text-align: right;" target="currentPath">currentPath:</label>
      <input style="margin-bottom: 40px;" class="flex" id="currentPath" placeholder="{{currentPath}}" disabled="true" />
    </div>
    <div style="height: 80px;" class="label-item">
      <label style="margin-right: 5px;width:200px;height: 60px;text-align: right;" target="selected">selected:</label>
      <input style="margin-bottom: 40px;" class="flex" id="selected" placeholder="{{selected}}" disabled="true" />
    </div>
  </div>
</template>
<style>
  .container {
    flex: 1;
    flex-direction: column;
  }
  .progress {
    flex: 1;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    padding-bottom: 20px;
  }
  input {
    width: 300px;
    height: 70px;
    background-color: #fffafa;
    border: 1px solid;
    margin-top: 40px;
    align-content: center;
    text-align: center;
  }
  .greenButton {
    background-color: #67C23A;
    margin-left: 5px;
    width: 150px;
    height: 60px;
    font-size: 30px;
  }
  .buleButton {
    background-color: #409EFF;
    margin-left: 5px;
    width: 150px;
    height: 60px;
    font-size: 30px;
  }
  .redButton {
    background-color: #F56C6C;
    margin-left: 5px;
    width: 150px;
    height: 60px;
    font-size: 30px;
  }
  .label-item {
    align-items: center;
    border-bottom-width: 1px;
    border-color: #dddddd;
    margin-top: 1px;
  }
  label {
    font-size: 30px;
    width: 400px;
    height: 70px;
  }
  .title {
    font-size: 30px;
  }
  .flex {
    width: 500px;
    height: 50px;
    border: 2px solid;
    font-size: 30px;
    padding-left: 10px;
  }
  .listItem {
    border: 2px solid;
    border-color: #dddddd;
    height: 60px;
  }
  .currentListItem {
    border: 5px solid;
    border-color: #67C23A;
    height: 60px;
  }
</style>
<script>
  import prompt from '@system.prompt';
  import media from '@system.media';
  import clipboard from '@system.clipboard';
  import router from '@system.router';
  module.exports = {
    data: {
      defaultConfig: '',
      minFetchIntervalMillis: 0,
      result: '',
      list: [],
      selected: '',
      currentPath: '',
      progress: 0,
      total: 0,
    },
    textClick(e) {
      this.selected = e.target.attr.id;
      this.getList();
    },
    longpress(e) {
      if (this.selected === e.target.attr.id) {
        this.selected = '';
      } else {
        this.selected = e.target.attr.id;
        this.result = e.target.attr.id;
      }
    },
    copyClick() {
      clipboard.set({
        text: this.result
      })
      prompt.showToast({
        message: `copy to clipboard success`,
        duration: 3500,
        gravity: 'center'
      });
    },
    getPath(fullPath) {
      if (fullPath.endsWith('/')) {
        return fullPath;
      } else {
        return fullPath.substring(0, fullPath.lastIndexOf('/') + 1);
      }
    },
    getName(fullPath) {
      if (!fullPath.endsWith('/')) {
        let start = fullPath.lastIndexOf('/');
        return fullPath.substring(start + 1, fullPath.length);
      }
      return null;
    },
    getParentPath() {
      if (this.currentPath === '') {
        return null;
      }
      let pathWithoutTrailingSlash = this.currentPath.substring(0, this.currentPath.length - 1);
      let parentpPath = pathWithoutTrailingSlash.substring(0, pathWithoutTrailingSlash.lastIndexOf('/') + 1);
      return parentpPath === '/' ? '' : parentpPath;
    },
    back() {
      if (this.currentPath === '') {
        prompt.showToast({
          message: `root dir can not back`,
          duration: 3500,
          gravity: 'center'
        });
        return;
      }
      let agconnect = this.$app.$def.agc;
      //创建存储示例对象的引用,通过引用调用相关的文件/目录接口
      let ref = agconnect.cloudStorage().storageReference();
      let parentPath = this.getParentPath();
      const child = ref.child(parentPath);
      child.list({ maxResults: 10 }).then((res) => {
        this.currentPath = parentPath;
        this.selected = '';
        this.setList(res);
      })
    },
    getList() {
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      let path = this.selected === '' ? this.currentPath : this.selected;
      const child = ref.child(path);
      child.list({ maxResults: 10 }).then((res) => {
        this.currentPath = path;
        this.selected = '';
        this.setList(res);
      })
    },
    getListAll() {
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      let path = this.selected === '' ? this.currentPath : this.selected;
      const child = ref.child(path);
      child.listAll().then((res) => {
        this.currentPath = path;
        this.selected = '';
        this.setList(res);
      })
    },
    setList(res) {
      let result = [];
      if (res.dirList) {
        for (var i in res.dirList) {
          result.push({
            name: res.dirList[i].name,
            path: res.dirList[i].path,
            isFile: false,
            select: false
          });
        }
      }
      if (res.fileList) {
        for (var j in res.fileList) {
          var item = {
            name: res.fileList[j].name,
            path: res.fileList[j].path,
            isFile: true,
            select: false
          }
          result.push(item);
        }
      }
      this.list = result;
      this.total = result.length;
      this.result = JSON.stringify(this.list, null, "\t");
      prompt.showToast({
        message: `query success`,
        duration: 3500,
        gravity: 'center'
      });
    },
    getMetaData() {
      if (this.selected === '') {
        prompt.showToast({
          message: `root file can not getMetaData`,
          duration: 3500,
          gravity: 'center'
        });
        return;
      }
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      const child = ref.child(this.selected);
      child.getFileMetadata().then((res) => {
        this.result = JSON.stringify(res, null, "\t");
        prompt.showToast({
          message: `getMetaData success`,
          duration: 3500,
          gravity: 'center'
        });
      })
    },
    uploadMetaData() {
      if (this.selected === '' || this.selected.endsWith('/')) {
        prompt.showToast({
          message: `only file can uploadMetaData`,
          duration: 3500,
          gravity: 'center'
        });
        return;
      }
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      const child = ref.child(this.selected);
      child.updateFileMetadata({
        cacheControl: 'no-cache',
        contentEncoding: 'identity',
        contentLanguage: 'en-US',
        customMetadata: {
          hello: 'kitty'
        }
      }).then((res) => {
        this.result = JSON.stringify(res, null, '\t');
        prompt.showToast({
          message: `uploadMetaData success`,
          duration: 3500,
          gravity: 'center'
        });
      })
    },
    getDownloadURL() {
      if (this.selected === '' || this.selected.endsWith('/')) {
        prompt.showToast({
          message: `only file can getDownloadURL`,
          duration: 3500,
          gravity: 'center'
        });
        return;
      }
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      const child = ref.child(this.selected);
      child.getDownloadURL().then((res) => {
        this.result = res;
        prompt.showToast({
          message: `getDownloadURL success`,
          duration: 3500,
          gravity: 'center'
        });
      }).catch((err) => {
        console.error("getDownloadURL fail");
        prompt.showToast({
          message: `getDownloadURL fail`,
          duration: 3500,
          gravity: 'center'
        });
      });
      var that = this
      prompt.showDialog({
        title: '',
        message: 'Do you want to download the file and view the content?',
        buttons: [
          {
            text: 'yes',
            color: '#33dd44'
          },
          {
            text: 'cancel',
            color: '#33dd44'
          }
        ],
        success: function (data) {
          console.log("handling callback", data);
          if (data.index === 0) {
            router.push({
              uri: '/DownloadShow',
              params: { url: that.result }
            })
          }
        },
        cancel: function () {
          console.log("cancel");
        }
      })
    },
    delete() {
      if (this.selected === '' || this.selected.endsWith('/')) {
        prompt.showToast({
          message: `only file can be delete`,
          duration: 3500,
          gravity: 'center'
        });
        return;
      }
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      const child = ref.child(this.selected);
      child.delete().then((res) => {
        prompt.showToast({
          message: `delete success`,
          duration: 3500,
          gravity: 'center'
        });
        let result = [];
        for (var i in this.list) {
          if (this.list[i].path !== this.selected) {
            result.push(this.list[i]);
          }
        }
        this.list = result;
        this.selected = '';
      })
    },
    putString() {
      let agconnect = this.$app.$def.agc;
      let ref = agconnect.cloudStorage().storageReference();
      //var raw = '我是需要保存到云端的字符串文件'
      //var base64 = '5oiR5piv6ZyA6KaB5L+d5a2Y5Yiw5LqR56uv55qE5a2X56ym5Liy5paH5Lu2' // 编码前:我叫江红平,请叫我大疆!
      //var base64url = '5oiR5piv6ZyA6KaB5L+d5a2Y5Yiw5LqR56uv55qE5a2X56ym5Liy5paH5Lu2' // 编码前:我叫江红平,请叫我大疆!
      var data_url = 'data:txt;base64,5oiR5piv6ZyA6KaB5L+d5a2Y5Yiw5LqR56uv55qE5a2X56ym5Liy5paH5Lu2'
      let path = this.currentPath + 'putStringFile.txt';
      const child = ref.child(path);
      var uploadTask = child.putString(data_url, 'data_url', {
        cacheControl: 'no-cache',
        contentDisposition: 'attachment;filename="putStringFile.txt"',
        contentEncoding: 'identity',
        contentLanguage: 'zh-CN',
        contentType: 'text/plain;charset=utf-8',
        customMetadata: {
          hello: 'world'
        }
      })
      this.printUploadPercent(uploadTask)
      uploadTask.then((UploadResult) => {
        this.result = JSON.stringify(UploadResult.metadata, null, "\t");
      }).catch(error => {
        console.log(error.message)
      })
    },
    putFile() {
      let that = this;
      media.pickFile({
        success: function (data) {
          console.log("handling success: " + data.uri);
          let agconnect = that.$app.$def.agc;
          let ref = agconnect.cloudStorage().storageReference();
          let path = that.currentPath + that.getName(data.uri);
          const child = ref.child(path);
          child.put4QuickApp(data.uri, {
            cacheControl: 'no-cache',
            //contentDisposition: 'attachment;filename="demo.png"',
            contentEncoding: 'identity',
            contentLanguage: 'en-US',
            //contentType: 'image/png; charset=utf-8',
            customMetadata: {
              hello: 'kitty'
            }
          }).then((res) => {
            that.result = JSON.stringify(res, null, "\t");
            prompt.showToast({
              message: `putFile success`,
              duration: 3500,
              gravity: 'center'
            });
          })
        },
        fail: function (data, code) {
          console.log("handling fail, code=" + code);
        }
      })
    },
    printUploadPercent(uploadTask) {
      let that = this;
      uploadTask.on('state_changed', function (snapshot) {
        if (snapshot.totalByteCount === 0) {
          return;
        }
        that.progress = (snapshot.bytesTransferred / snapshot.totalByteCount) * 100;
        console.log('Upload is ' + that.progress.toFixed(1) + '% done')
        switch (snapshot.state) {
          case 'paused':
            prompt.showToast({
              message: `Upload is paused`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'running':
            prompt.showToast({
              message: `Upload is running`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'success':
            prompt.showToast({
              message: `Upload is success`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'canceled':
            prompt.showToast({
              message: `Upload is canceled`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'error':
            prompt.showToast({
              message: `Upload is error`,
              duration: 3500,
              gravity: 'center'
            });
            break
        }
      }, function (snapshot) {
        switch (snapshot.state) {
          case 'paused':
            prompt.showToast({
              message: `Upload is paused`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'running':
            prompt.showToast({
              message: `Upload is running`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'success':
            prompt.showToast({
              message: `Upload is success`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'canceled':
            prompt.showToast({
              message: `Upload is canceled`,
              duration: 3500,
              gravity: 'center'
            });
            break
          case 'error':
            prompt.showToast({
              message: `Upload is error`,
              duration: 3500,
              gravity: 'center'
            });
            break
        }
      }, function () {
        prompt.showToast({
          message: `Upload is success`,
          duration: 3500,
          gravity: 'center'
        });
      })
    }
  }
</script>

hello.ux

<template>
  <div class="container">
    <image src="/Common/cloudstorage.png" style="height:400px;object-fit: contain"></image>
    <input style="width:300px;height:100px;" type="button" value="Login" @click="signInAnonymously" />
  </div>
</template>
<style>
  .container {
    flex-direction: column;
    justify-content: center;
    align-content: center;
    align-items: center;
  }
  input {
    width: 500px;
    height: 150px;
    background-color: #fffafa;
    border: 1px solid #aaaaaa;
    margin-top: 80px;
  }
</style>
<script>
  import prompt from '@system.prompt';
  module.exports = {
    data: {
      title: 'World'
    },
    signInAnonymously() {
      let agconnect = this.$app.$def.agc;
      agconnect
        .auth()
        .signInAnonymously()
        .then((res) => {
          console.log('loginA res', res)
          prompt.showToast({
            message: `login success`,
            duration: 3500,
            gravity: 'center'
          });
          var router = require("@system.router")
          router.push({
            uri: '/Main',
            params: { body: " test send message" }
          })
        })
        .catch((err) => {
          console.log('loginA', err)
          prompt.showToast({
            message: `login failed`,
            duration: 3500,
            gravity: 'center'
          });
        })
    }
  }
</script>

download.ux

<template>
    <div>
        <text show="{{this.fileType==='txt'}}">{{this.textContent}}</text>
        <image show="{{this.fileType==='png'|| this.fileType==='jpg'||this.fileType==='svg'||this.fileType==='gif'}}" src="{{this.filePath}}"></image>
        <video show="{{this.fileType==='mp4'|| this.fileType==='3gp'||this.fileType==='ts'||this.fileType==='mkv'||this.fileType==='ogg'}}" src="{{this.filePath}}" controls="true"></video>
        <div show="{{this.fileType==='mp3'|| this.fileType==='m4a' || this.fileType==='wav'}}" class="container">
            <div class="item_container">
                <image src="/Common/play.png" style="width:50px;height:50px;margin-right:50px;" onclick="play"></image>
                <text>{{time}}</text>
                <text style="margin-left:6px;margin-right:6px;">/</text>
                <text style="margin-right:50px;">{{total}}</text>
                <image src="/Common/pause.png" style="width:50px;height:50px;" onclick="pause"></image>
            </div>
            <input type="button" style="background-color:#09ba07;margin-bottom:20px;" onclick="autoPlay" value="autoPlay" />
            <input type="button" style="background-color:#09ba07;margin-bottom:20px;" onclick="manualPlay" value="manualPlay" />
            <input type="button" style="background-color:#09ba07;margin-bottom:20px;" onclick="setMute" value="set muted?" />
            <input type="button" style="background-color:#09ba07;margin-bottom:20px;" onclick="seek" value="seek" />
        </div>
    </div>
</template>
<style>
    @import "../Common/css/common1.css";
    .item_container {
        margin-bottom: 50px;
        margin-right: 60px;
        margin-left: 60px;
        flex-direction: row;
        height: 300px;
    }
    .item {
        height: 250px;
        text-align: center;
        color: #ffffff;
    }
    image {
        object-fit: contain;
    }
</style>
<script>
    import request from '@system.request'
    import file from '@system.file'
    import audio from '@system.audio'
    import router from '@system.router';
    module.exports = {
        data: {
            url: "",
            filePath: "",
            fileType: "",
            textContent: "",
            time: 0,
            total: 0,
        },
        onInit() {
            this.$page.setTitleBar({ text: 'DownloadShow' })
        },
        onShow: function () {
            var that = this
            console.log("download url: " + that.url);
            request.download({
                url: that.url,
                success: function (data) {
                    console.log("request success" + data.token);
                    request.onDownloadComplete({
                        token: data.token,
                        success: function (data) {
                            console.log("download success, " + data.uri);
                            that.filePath = data.uri;
                            let start = that.filePath.lastIndexOf('.');
                            that.fileType = that.filePath.substring(start + 1);
                            console.log("fileType = " + that.fileType);
                            if (that.fileType === 'txt') {
                                file.readText({
                                    uri: that.filePath,
                                    success: function (data) {
                                        console.log('readText success. text = ' + data.text);
                                        that.textContent = data.text;
                                    },
                                    fail: function (errmsg, errcode) {
                                        console.log('readText failed ' + errmsg + ' errcode = ' + errcode);
                                    }
                                })
                            }
                            if (that.fileType === 'mp3' || that.fileType === 'm4a' || that.fileType === 'wav') {
                                audio.src = that.filePath;
                                audio.play();
                            }
                        },
                        fail: function (data, code) {
                            console.log("download fail, code=" + code);
                        }
                    })
                },
                fail: function (data, code) {
                    console.log("request fail, code=" + code);
                }
            })
        },
        autoPlay: function () {
            var that = this;
            var srcUri = that.filePath;
            audio.src = srcUri;
            audio.volume = 0.2;
            var isshow = that.notify;
            audio.notificationVisible = isshow;
            audio.autoplay = true;
            audio.loop = true;
            audio.onplay = function () {
                console.log("audio onplay");
            };
            audio.onpause = function () {
                console.log("audio onpause");
            };
            audio.onended = function () {
                console.log("audio onended");
            };
            audio.ondurationchange = function () {
                console.log("audio ondurationchange");
                that.total = audio.duration;
                console.log("audio ondurationchange total=" + that.total);
            };
            audio.ontimeupdate = function () {
                that.time = audio.currentTime;
                console.log("audio ontimeupdate time=" + that.time);
            };
        },
        manualPlay: function () {
            var that = this;
            var s = that.filePath;
            audio.src = s;
            audio.play();
            audio.onplay = function () {
                console.log("audio onplay");
            };
            audio.onpause = function () {
                console.log("audio onpause");
            };
            audio.onended = function () {
                console.log("audio onended");
            };
            audio.ondurationchange = function () {
                console.log("audio ondurationchange");
                that.total = audio.duration;
            };
            audio.ontimeupdate = function () {
                console.log("audio ontimeupdate");
                that.time = audio.currentTime;
            };
        },
        play: function () {
            audio.play();
        },
        pause: function () {
            audio.pause();
        },
        setMute: function () {
            var that = this;
            var isMuted = !that.muted;
            that.muted = isMuted;
            audio.muted = isMuted;
        },
        seek: function () {
            audio.currentTime = 288;
        }
    }
</script>