快應用接入雲存儲服務指導


1. 雲存儲服務介紹

雲存儲是一種可伸縮、免維護的雲端存儲服務,您可以用於存儲圖片、音頻、視頻或其他由用戶生成的內容。借助雲存儲服務,您可以無需關心存儲服務器的開發、部署、運維、擴容等事務,大大降低了應用使用存儲的門檻,讓您可以專注於應用的業務能力構建,助力您的商業成功。

工作原理:

您的應用客戶端使用雲存儲服務提供的 SDK,可以向雲存儲服務器上傳文件,雲存儲將您上傳的文件存儲在默認的存儲實例中。您可以通過 AGC 訪問這些文件。當然,您還可以使用雲存儲 SDK 的 API 執行下載、刪除、管理文件等操作。雲存儲還可以配合雲函數,在雲存儲的文件上傳完成或刪除成功后觸發雲函數執行您想要實現的功能。

典型應用場景:

存儲海量文件信息,提供跨平台高效上傳下載服務

雲存儲服務提供簡單易用、功能強大的端/雲SDK,實現用戶生成內容的存儲,讓您無需關注雲端能力的構建而聚焦業務邏輯開發。

2. 快應用接入雲存儲開發流程

開發流程概覽

申請和開通雲存儲服務

  • 申請雲存儲服務

雲存儲服務當前仍處於 Beta 開放狀態,在使用此服務前,您需要向 agconnect@huawei.com 發送申請郵件,申請開通雲存儲服務。

郵件標題請使用如下格式:“[雲存儲]-[公司名稱]-[開發者帳號ID]-[項目ID]”

  • 開通雲存儲服務

登錄 AppGallery Connect 網站,點擊“我的項目”。

在項目列表中點擊需要開通雲存儲的項目。

選擇“構建 > 雲存儲”,點擊“立即開通”。

在引導界面輸入存儲實例名稱和選擇“默認數據處理位置”,選擇“默認安全策略”。

單擊“完成”,開通雲存儲成功。

新建Serverless項目

1. 打開快應用 IDE,在歡迎頁點擊登錄,在跳轉的網頁中登錄注冊的帳號。

2. 登錄成功后,IDE 的導航選擇“新建工程 > 快應用·雲開發”,選擇關聯應用、模板,設置項目路徑后,點擊“確定”。

將應用配置信息添加到項目

1. 登錄 AppGallery Connect 網站,選擇“我的項目”。

2. 在項目列表中找到您的項目,並點擊需要集成雲存儲服務的快應用。

3. 在“項目設置”頁面中選擇“常規”頁簽,下載配置文件“agconnect-services.json”。

4. 檢查 agconnect-services.json 文件中 "service > cloudstorage" 標簽中是否已默認配置 default_storage。

"cloudstorage" : { 
    "default_storage" : "您准備默認使用的存儲實例名稱",
    "storage_url" : "https://agc-storage-drcn.platform.dbankcloud.cn" 
}

5. 將修改后 agconnect-services.json 拷貝到您快應用項目的 src 目錄下。

集成SDK

1. 執行如下命令安裝雲存儲 JS SDK 到您的項目中。

npm install --save @agconnect/cloudstorage@1.1.0

 2. 在您的項目中導入 agc 組件。

import agconnect from '@agconnect/api';
import '@agconnect/cloudstorage';
import "@agconnect/instance";

3. 初始化 AGC SDK。 

let agConnectConfig = require('./agconnect-services.json');
agconnect.instance().configInstance(agConnectConfig);

4. 初始化存儲實例

const storageManagement = agconnect.cloudStorage();

創建引用

1. 文件存儲在雲端的存儲實例中,存儲方式與本地硬盤中的文件系統類似,您可以通過文件的引用進行上傳文件、獲取文件的下載地址、刪除文件、更新文件元數據等操作,您也可以通過創建目錄的引用來獲取該目錄下的文件列表。

如果您需要上傳、刪除文件,更新文件的元數據及獲取文件的下載地址,均需要創建對應文件的引用。

2. 初始化成功后,您可通過調用 StorageManagement.storageReference 創建 StorageReference 對象的引用。

// storageManagement為已經初始化的cloudStorage實例
const reference = storageManagement.storageReference();

3. 您也可以通過調用 StorageManagement.storageReference 並傳入一個完整的雲端文件的地址來創建一個 StorageReference 對象的引用。

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);
})

上傳文件

1. 用戶可以通過引用操作本地設備上的文件,將文件上傳到雲端的存儲實例中。

2. 調用 StorageManagement.storageReference 創建需上傳文件的引用,傳入文件在雲端預先規划的文件地址。

var storageReference = storage.storageReference();
var reference = storageReference.child('images/demo.jpg');

3. 調用 StorageReference.put4QuickApp 方法將文件上傳到存儲實例中。

// uri為本地文件資源uri標識
var fileMetadata = reference.put4QuickApp(uri);

4. 如果您需要在上傳文件時為文件指定自定義屬性,可以使用 StorageReference.put4QuickApp(uri : String, , attribute ?: UploadMetadata) 方法中的 UploadMetadata 屬性。

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);
        }
    })
},

列舉文件

1. 雲存儲 SDK 支持通過 API 列舉雲端某個目錄下的所有文件或子目錄。

2. 在列舉某個目錄下的文件或目錄前,先調用 StorageManagement.storageReference 創建目錄的引用。例如創建根目錄的引用:

var storageReference = storage.storageReference();

3. 調用 StorageReference.listAll 可獲取當前目錄下所有文件與目錄。

reference.listAll()
    .then((res) => {})
    .catch((err) => {});

4. 如果需要分頁獲取,可以調用 StorageReference.list(options?: ListOptions) 方法。

// pageMarker是獲取分頁列表信息時下一頁的起始位置
reference.list ({
    maxResults: 100,
	pageMarker: pageMarker
}).then((res) = >{}).catch((err) = >{});
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);
	})
},

獲取文件的下載地址

1. 文件已經上傳到雲端后,您可以通過調用雲存儲 SDK 的 API 獲取雲端文件的下載地址。

2. 調用 StorageManagement.storageReference 創建需要下載文件的引用。

var storageReference = storage.storageReference();
var reference = storageReference.child('images/demo.jpg');

3. 調用 StorageReference.getDownloadURL 獲取下載地址。

reference.getDownloadURL()
    .then(function(downloadURL){})
    .catch((err) => {});

4. 您可以通過將上一步獲取的下載地址拷貝到瀏覽器的地址欄下載文件,或者調用快應用下載接口獲取文件。

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");
        }
    })
}

刪除文件

1. 當雲端的文件不需要時,您可以通過調用雲存儲 SDK 的 API 在應用客戶端刪除雲端的文件。

2. 調用 StorageManagement.storageReference 創建需要刪除文件的引用。

var storageReference = storage.storageReference();
var reference = storageReference.child('images/demo.jpg');

3. 調用 StorageReference.delete 刪除雲端文件。 

reference.delete()
    .then((res) => {})
    .catch((err) => {});

注意:刪除操作不可逆,一旦執行,文件會被物理刪除,不可找回。

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 = '';
    })
},

元數據管理

1. 在上傳文件前或者文件已經上傳到雲端,您都可以設置文件元數據。可設置的文件元數據包括文件的自定義屬性。

2. 調用 StorageManagement.storageReference 創建文件的引用,並初始化文件的 UploadMetadata 實例。

var storageReference = storage.storageReference();
var reference = storageReference.child('images/demo.jpg');
var metadata = { contentType:'image/jpeg' };
// uri為本地文件資源uri標識
var fileMetadata = reference.put4QuickApp(uri, metadata);

3.文件的自定義屬性可以通過 UploadMetadata.customMetadata 設置。

調用 StorageReference.updateFileMetadata 采用覆蓋的方式將設置的文件元數據覆蓋到雲端。

reference.updateFileMetadata(metadata)
    .then(function(res){})
    .catch((err) => {});

4. 當設置元數據成功后,您可以通過調用 StorageReference.getFileMetadata 方法來獲取設置在雲端的元數據。

reference.getFileMetadata()
    .then((res) => {})
    .catch((err) => {});
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'
        });
    })
},

3. AGC 控制台管理文件

AGC 的雲存儲服務提供可視化的文件管理和數據分析功能。

文件管理:除了在應用客戶端通過雲存儲SDK的API來管理文件,您還可以直接在AGC以可視化的方式來進行文件管理,包括上傳文件、查看文件詳情、下載文件、創建文件夾、刪除文件或文件夾、創建令牌。

數據分析:您可以在AGC中查看雲存儲數據分析情況。

AGC 控制台目前支持以下功能:

  • 上傳文件
  • 創建文件夾
  • 查看文件詳情
  • 下載文件
  • 刪除文件或文件夾
  • 創建令牌
  • 雲存儲數據分析

4. FAQ

配額限制

當您使用的雲存儲資源超過免費配額后,則需要付費使用超額的部分,具體請參見服務定價與訂購。

資源限制

Q:是否支持流式文件上傳?

采用流式上傳文件沒辦法對文件進行一致性校驗,容易造成文件損壞,可采用先接收數據並寫入文件,然后再通過本地文件上傳到雲端的方式上傳文件。

Q:雲端文件的命名是否有限制?

滿足命名規范即可,無其他限制,但服務器會按照文件名的 UTF-8 編碼范圍進行分區管理,對系統進行水平擴展與動態負載均衡。如果文件命名規則使用了順序前綴(如時間戳或字母順序),可能導致大量文件的請求訪問集中於某個特定分區,造成訪問熱點,熱點分區上的請求速率受限,訪問時延上升。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM