云函数
云函数提供FaaS(Function as a Service)能力,开发者无需自建服务器,只需聚焦业务逻辑、开发并上传函数代码,即可构建高可用、可伸缩的Serverless应用。使用云函数可以帮助开发者大幅简化应用开发与传统运维相关的事务,降低应用功能的实现门槛,快速构建业务能力。
云数据库
云数据库提供托管在云端的数据存储服务,采用基于对象模型的数据存储结构,支持单个或批量操作对象,如新增、修改、删除和查询等丰富的API接口。
云存储
云存储是专为开发者打造的可伸缩、免维护的云端存储服务,开发者可以用于存储图片、音频、视频或其他由用户生成的内容。
认证服务
大部分的应用都需要对用户的业务访问进行身份认证,以便为用户提供个性化体验。但是端到端完整构建一套用户认证系统会面临很多挑战。认证服务可以为您的应用快速构建安全可靠的用户认证系统,您只需在应用中访问认证服务的相关能力,而不需要关心云侧的设施和实现。
认证服务为云函数、云数据库、云存储等服务提供了全面且自适应的安全支撑,可令您对用户数据的保护事半功倍。

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

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

新建项目结构主要由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名称 | 版本 |
|---|---|---|
| 认证服务 | @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"
}cd client npm install
安装完成后,在左侧导航目录将生成node_modules目录。

util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || this || global; // eslint-disable-line no-invalid-this
在进行云函数开发前,需进行同步云函数操作,以便将在HarmonyOS 开发者中心配置的云端云函数列表同步到IDE。
选择云函数主目录cloudfunctions,右击鼠标选择“同步云函数列表”。

同步完成后,在项目导航树的cloudfunctions目录下生成以云函数名命名的文件夹。
此操作不会下载云函数代码。
创建云函数

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

修改云函数
如下图所示,在终端页签进入云函数目录,执行npm命令下载依赖后,在云函数目录下的package.json文件中增加依赖配置信息,在云函数的node_modules目录下生成以第三方依赖命名的目录。
函数部署包需要使用如下结构,处理程序所在代码文件必须在zip根目录下,依赖项放到这node_modules目录下。
my-function.zip
|—— index.js
|—— node_modules
|—— async
|—— async-listener
删除云函数
删除函数会将函数的所有版本、别名数据删除,函数删除后数据不可恢复。

$latest版本
首次创建函数,版本默认为$latest。
开发者只能基于$latest版本修改并发布版本,发布的版本不支持修改,只支持查看和删除。发布后展示的版本号从1开始递增。
例如,首次创建后版本为$latest,将$latest版本发布为版本1。一段时间后需要为函数增加新的功能,可以在$latest版本中修改,并将修改后的版本发布为版本2。开发者可以调用版本1和版本2的函数实现不同的功能。
发布版本
将测试通过的云函数发布为正式版本,每个云函数可以发布多个版本。
删除版本
,删除版本。 
创建别名
通过创建别名,可以将云函数和指定发布的版本关联起来。

修改、删除别名
,删除别名。点击编辑图标
,修改别名信息。 
为云函数的别名创建HTTP触发器的步骤如下。

在指定时间点定时触发云函数时,需创建CRON类型触发器。
| 格式 | 说明 |
|---|---|
| 以“@every ValueUnit”格式 | Value为一个正整数,Unit可以为“s”、“m”、“h”,表示每隔ValueUnit的时间触发一次函数。例如,“@every 6m” 表示每隔6分钟触发一次函数。 |
| 通过kubernetes cronjob支持的标准的cron表达式的形式(Minutes Hours Day-of-month Month Day-of-week )设置 |
说明: cron以UTC时间运行,即北京时间减去8个小时。 常用设置示例如下:
|

调用云函数分触发器调用和应用客户端调用两种方式。
import agconnect from '@agconnect/api'; import '@agconnect/function'; import "@agconnect/instance";
let agConnectConfig = require('./agconnect-services.json');
agconnect.instance().configInstance(agConnectConfig);
调用云函数时,强烈建议通过云函数别名进行调用。这样当云函数变动升级后,只需修改别名中指定的版本即可。
let functionCallable = agconnect.function().wrap("functionname-functionalias");//functionname-functionalias为云函数别名对应的HTTP触发器标识
let reqBody = {"data":"value"};
let functionResult = await functionCallable.call(reqBody);
let returnValue = functionResult.getValue();
更多接口请参见“云函数API”。

"cloudstorage":{
"default_storage":"storagetest1-10do4-skqea",
"storage_url":"https://agc-storage-drcn.platform.dbankcloud.cn"
}let agConnectConfig = require('./agconnect-services.json');
agconnect.instance().configInstance(agConnectConfig);const storageManagement = agconnect.cloudStorage();
更多接口介绍请参见“云存储API”。
const context = require('../agconnect-services.json');更多接口介绍请参见“云数据库API”。
<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> <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> 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>