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

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、文件下载结果

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仙魁XAN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值