Unity 阿里云 之 OSS对象存储功能的接入 之 获取文件列表,下载文件

 

目录

Unity 阿里云 之 OSS对象存储功能的接入 之 获取文件列表,下载文件

一、简介和目的

二、实现要点

三、使用注意

四、测试效果

五、实现步骤


 

一、简介和目的

海量、安全、低成本、高可靠的云存储服务,提供99.9999999999%的数据可靠性。使用RESTful API 可以在互联网任何位置存储和访问,容量和处理能力弹性扩展,多种存储类型供选择全面优化存储成本。

在Unity可用于文件的上传下载,只要引入对应的 dll 文件即可使用,很是方便。

同时,根据需要获取对象中的所有文件,然后可以批量下载文件。

二、实现要点

1、在阿里云下载SDK,得到里面的 Aliyun.OSS.dll,引入Unity

2、在OSS对象存储 中已经有 Bucket,和 对应的数据

3、需要申请阿里云 AccessKey

4、关键代码
 

 ossClient = new OssClient(...);
 
 ObjectListing listing = ossClient.ListObjects(Config.Bucket);
 
 public class Config
 {
    public const string AccessKeyId = "<accessKeyId>"; 
    public const string AccessKeySecret = "<accessSecret>";
    public const string EndPoint = "oss-cn-shenzhen.aliyuncs.com";
    public const string Bucket = "aliyunoss1116";
 
 }

三、使用注意

1、注意:在下载大文件的时候,请使用线程,避免主线程卡顿

2、注意:在使用多线程的时候,注意 UI 相关必须在 主线程中,不然会报错

3、注意:可以使用正则表达式过滤掉一些不需要的文件或者文件夹

四、测试效果

五、实现步骤

1、登陆阿里云平台,找到 对象存储 OSS

2、点击进入后,进入 管理控制台

 

3、下载SDK,解压SDK包,然后 把 Aliyun.OSS.dll 引入Unity

 

4、对了,如果没有 AccessKey ,记得申请一个

5、打开创建好的 Bucket ,在文件管理里面目前大概有如下文件,待会代码获取对应的文件列表

6、代码获取上面的Bucket 文件列表数据

using Aliyun.OSS;
using Aliyun.OSS.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using UnityEngine;


public class AliyunOSS_GetList : MonoBehaviour
{


    OssClient ossClient;
    
    // Start is called before the first frame update
    void Start()
    {
        ossClient = new OssClient(Config.EndPoint, Config.AccessKeyId,         Config.AccessKeySecret);
        
    }

    // Update is called once per frame
    void Update()
    {
        

        if (Input.GetKeyDown(KeyCode.G)) {
            foreach (var item in GetFileList()) {
                Debug.Log(item);
            }
        }
    }

    /// <summary>
    /// 获取对应 Bucket 的文件列表
    /// </summary>
    /// <returns></returns>
    public List<string> GetFileList() {
        ObjectListing listing = ossClient.ListObjects(Config.Bucket);
        List<string> nameList = new List<string>();

        foreach (var item in listing.ObjectSummaries) {

            // 过滤掉文件夹
            if (Regex.IsMatch(item.Key,"/") == false) {
                nameList.Add(item.Key);

            }
        }

        return nameList;
    }
   
}

 
 public class Config
 {
    public const string AccessKeyId = "<accessKeyId>"; 
    public const string AccessKeySecret = "<accessSecret>";
    public const string EndPoint = "oss-cn-shenzhen.aliyuncs.com";
    public const string Bucket = "aliyunoss1116";
 
 }

7、获得列表数据后,进行对应下载,首先在Unity中新建UI布局

8、对应脚本代码如下

using Aliyun.OSS;
using Aliyun.OSS.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class AliyunOSS_GetList : MonoBehaviour
{
    public Button getList_button;
    public GameObject itemGo;
    public GameObject itemGoParent;


    OssClient ossClient;
    
    // Start is called before the first frame update
    void Start()
    {
        ossClient = new OssClient(Config.EndPoint, Config.AccessKeyId, Config.AccessKeySecret);
        getList_button.onClick.AddListener(()=> {
            foreach (var item in GetFileList())
            {
                Debug.Log(item);
                Instantiate(itemGo,itemGoParent.transform).
                GetComponent<ItemGetObject>().SetFileName(item);
            }
        });
    }

    // Update is called once per frame
    void Update()
    {
        

        if (Input.GetKeyDown(KeyCode.G)) {
            foreach (var item in GetFileList()) {
                Debug.Log(item);
            }
        }
    }

    /// <summary>
    /// 获取对应 Bucket 的文件列表
    /// </summary>
    /// <returns></returns>
    public List<string> GetFileList() {
        ObjectListing listing = ossClient.ListObjects(Config.Bucket);
        List<string> nameList = new List<string>();

        foreach (var item in listing.ObjectSummaries) {

            // 过滤掉文件夹
            if (Regex.IsMatch(item.Key,"/") == false) {
                nameList.Add(item.Key);

            }
        }

        return nameList;
    }


   
}

 public class Config
 {
    public const string AccessKeyId = "<accessKeyId>"; 
    public const string AccessKeySecret = "<accessSecret>";
    public const string EndPoint = "oss-cn-shenzhen.aliyuncs.com";
    public const string Bucket = "aliyunoss1116";
 
 }
using Aliyun.OSS;
using Aliyun.OSS.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;


public class ItemGetObject : MonoBehaviour
{
    public Button getObject_button;
    public Text fileName_text;
    public Image process_image;

    string filePath;
    string savePath;
    Thread thread;
    Action<float> GetObjectProcessCallback;
    float getObjectProcess = 0;


    OssClient ossClient;
    // Start is called before the first frame update
    void Start()
    {
        ossClient = new OssClient(Config.EndPoint, Config.AccessKeyId, Config.AccessKeySecret);
        getObject_button.onClick.AddListener(
            () =>
            {
                GetObjectByThread((process) => {
                    Debug.Log("进度:" + process);
                    process_image.fillAmount = process;
                    
                },
                fileName_text.text,
                @"C:\Users\Administrator\Desktop\" + fileName_text.text
                );

            });
    }

    // Update is called once per frame
    void Update()
    {
        
        if (GetObjectProcessCallback != null)
        {
            GetObjectProcessCallback(getObjectProcess);

            if (getObjectProcess >= 1)
            {
                GetObjectProcessCallback = null;
                getObjectProcess = 0.0f;
            }
        }
    }

    public void GetObjectByThread(Action<float> action, string filePath, string savePath)
    {
        this.GetObjectProcessCallback = action;
        this.filePath = filePath;
        this.savePath = savePath;
        thread = new Thread(GetObject);
        thread.Start();
    }

    void GetObject()
    {
        try
        {
            GetObjectRequest getObjectRequest = new GetObjectRequest(Config.Bucket, filePath);
            getObjectRequest.StreamTransferProgress += StreamProcess;
            OssObject result = ossClient.GetObject(getObjectRequest);
            using (var resultStream = result.Content)
            {
                using (var fs = File.Open(savePath, FileMode.OpenOrCreate))
                {
                    int length = (int)resultStream.Length;
                    byte[] bytes = new byte[length];
                    do
                    {
                        length = resultStream.Read(bytes, 0, length);
                        fs.Write(bytes, 0, length);

                    } while (length != 0);

                }

                Debug.Log("下载成功");
            }
        }
        catch (OssException e)
        {
            print("进度下载文件出错:" + e.Message);
        }
        catch (Exception e)
        {
            print("进度下载文件出错:" + e.Message);
        }
        finally
        {

            thread.Abort();

        }

    }

    private void StreamProcess(object sender, StreamTransferProgressArgs args)
    {
        getObjectProcess = (args.TransferredBytes * 100 / args.TotalBytes) / 100.0f;
    }


    public void SetFileName(string fileName) {
        fileName_text.text = fileName;
    }
}

9、运行效果

10、文件下载结果

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐