C#阿里云OSS文件上传下载等操作(unity可用)

链接:官网SDK下载.
OSS全局配置

public class OssConfig
    {
        public const string AccessKeyId = "xxxxxxxxx";
        public const string AccessKeySecret = "xxxxxxxxxxx";
        public const string EndPoint = "xxxxxxxxxxxx";
        public const string Bucket = "xxxxxxxxxxxxxx";
    }

OSS本地实例

using Aliyun.OSS;
namespace AliyunOSS
{
    public class LocalOSSClient
    {
        private static OssClient _ossClient;
        private static readonly object _synclock = new object();

        public static OssClient OssClient
        {
            get
            {
                if (_ossClient == null)
                {
                    lock (_synclock)
                    {
                        if (_ossClient == null)
                        {
                            _ossClient = new OssClient(OssConfig.EndPoint, OssConfig.AccessKeyId,
                                OssConfig.AccessKeySecret);
                        }
                    }
                }

                return _ossClient;
            }
        }
    }
}

文件上传

using System;
using System.Threading;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using System.IO;

namespace AliyunOSS
{
    public class AliyunOSSUpLoader
    {
        public static void UpLoad(string fullFilePath, string ossPath, Action complete, Action<float> process = null)
        {
            PutObjectWithProcessByThread(fullFilePath, ossPath, complete, process);
        }

        public void UpLoad(string fullFilePath, string ossPath, Action complete)
        {
            PutObjectWithProcessByThread(fullFilePath, ossPath, complete);
        }

        private static void PutObjectWithProcessByThread(string fullFilePath, string ossPath, Action complete,
            Action<float> action = null)
        {
            Thread putLocalThread = null;
            putLocalThread = new Thread(() =>
            {
                try
                {
                    using (var fs = File.Open(fullFilePath, FileMode.Open))
                    {
                        PutObjectRequest putObjectRequest = new PutObjectRequest(OssConfig.Bucket, ossPath, fs);
                        putObjectRequest.StreamTransferProgress += (obg, args) =>
                        {
                            float putProcess = (args.TransferredBytes * 100 / args.TotalBytes) / 100.0f;
                            action?.Invoke(putProcess);
                            if (putProcess >= 1)
                            {
                                complete?.Invoke();
                                putObjectRequest.StreamTransferProgress = null;
                            }
                        };
                        LocalOSSClient.OssClient.PutObject(putObjectRequest);
                    }
                }
                catch (OssException e)
                {
                    Console.WriteLine("上传错误:" + e);
                }
                catch (Exception e)
                {
                    Console.WriteLine("上传错误:" + e);
                }
                finally
                {
                    putLocalThread.Abort();
                }
            });
            putLocalThread.Start();
        }
    }

文件上传URL获得

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AliyunOSS
{
    /// 
    /// 通过文件名获得文件的下载链接
    /// 
    public class OssUrlUtility
    {
        public static string GetFileUrl(string fileFullName)
        {
            string url = "http://" + OssConfig.Bucket + "." + OssConfig.EndPoint + "/" + fileFullName;
            return url;
        }
    }
}

文件下载

using System;
using System.IO;

namespace AliyunOSS
{
    public class OSSDownLoadHandler
    {
        /// 
        /// 
        /// 
        ///  OOS服务器里边存放的要下载的文件全路径 
        ///  存储到本地的文件路径,需包含后缀 
        public static void DownLoadFiles(string objName, string saveFullPathWithExtension)
        {
            var client = LocalOSSClient.OssClient;
            try
            {
                var obj = client.GetObject(OssConfig.Bucket, objName);
                using (var requestStream = obj.Content)
                {
                    byte[] buf = new byte[1024];
                    var fs = File.Open(saveFullPathWithExtension, FileMode.OpenOrCreate);
                    var len = 0;
                    while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                    {
                        fs.Write(buf, 0, len);
                    }

                    fs.Close();
                }

                Console.WriteLine("Get object succeeded:" + saveFullPathWithExtension);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Get object failed. {0}", ex.Message));
            }
        }
    }
}

文件信息

using System;
using System.Collections.Generic;
using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace AliyunOSS
{
    public class OSSFiles
    {

        /*ListObjectsRequest参数:
         objectSummaries	限定返回的文件元信息。
         prefix	本次查询结果的前缀。
         delimiter	对文件名称进行分组的一个字符。
         marker	标明本次列举文件的起点。
         maxKeys	列举文件的最大个数。
         nextMarker	下一次列举文件的起点。
         isTruncated	指明列举文件是否被截断。列举完没有截断,返回值为false。没列举完就有截断,返回值为true。
         commonPrefixes	以delimiter结尾,且有共同前缀的文件集合。
         encodingType	指明返回结果中编码使用的类型。*/

        /// 
        /// 简单列取100条
        /// 
        public static void ShowSampleOSSFileList()
        {
            var client = LocalOSSClient.OssClient;
            try
            {
                var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket);
                // 简单列举存储空间下的文件,默认返回100条记录。
                var result = client.ListObjects(listObjectsRequest);
                foreach (var summary in result.ObjectSummaries)
                {
                    Console.WriteLine(string.Format("File name:{0}", summary.Key));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("List objects failed. {0}", ex.Message));
            }
        }

        public static void ShowSpecifyFiles(int maxKeys = 200)
        {

            var client = LocalOSSClient.OssClient;
            try
            {
                var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket)
                {
                    // 最大返回200条记录。
                    MaxKeys = maxKeys,
                };
                var result = client.ListObjects(listObjectsRequest);
                Console.WriteLine("List objects succeeded");
                foreach (var summary in result.ObjectSummaries)
                {
                    Console.WriteLine(summary.Key);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("List objects failed, {0}", ex.Message));
            }
        }

        public static void ShowPrefixFiles(string prefix)
        {
            var client = LocalOSSClient.OssClient;
            try
            {
                var keys = new List<string>();
                ObjectListing result = null;
                string nextMarker = string.Empty;
                do
                {
                    var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket)
                    {
                        Marker = nextMarker,
                        MaxKeys = 100,
                        Prefix = prefix,
                    };
                    result = client.ListObjects(listObjectsRequest);
                    foreach (var summary in result.ObjectSummaries)
                    {
                        keys.Add(summary.Key);
                    }
                    nextMarker = result.NextMarker;
                } while (result.IsTruncated);

                foreach (var fSummary in result.ObjectSummaries)
                {
                    Console.WriteLine(fSummary.Key);
                }
                Console.WriteLine(string.Format("List objects of bucket:{0} succeeded ", OssConfig.Bucket));
            }
            catch (OssException ex)
            {
                Console.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
            }
        }
        public static void ShowSpecifyExtensionFiles(string maker)
        {
            var client = LocalOSSClient.OssClient;
            try
            {
                var keys = new List<string>();
                ObjectListing result = null;
                string nextMarker = maker;
                do
                {
                    var listObjectsRequest = new ListObjectsRequest(OssConfig.Bucket)
                    // 若想增大返回文件数目,可以修改MaxKeys参数,或者使用Marker参数分次读取。
                    {
                        Marker = nextMarker,
                        MaxKeys = 100,
                    };
                    result = client.ListObjects(listObjectsRequest);
                    foreach (var summary in result.ObjectSummaries)
                    {
                        keys.Add(summary.Key);
                    }
                    nextMarker = result.NextMarker;
                    // 如果IsTruncated为 true, NextMarker将作为下次读取的起点。
                } while (result.IsTruncated);

                foreach (var fSummary in result.ObjectSummaries)
                {
                    Console.WriteLine(fSummary.Key);
                }
                Console.WriteLine(string.Format("List objects of bucket:{0} succeeded ", OssConfig.Bucket));
            }
            catch (OssException ex)
            {
                Console.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
            }
        }
    }
}

文件操作

using System;
using System.Collections.Generic;
using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace AliyunOSS
{
    public class AliyunOSSHelper
    {
        /// 
        /// 删除单个文件
        /// 
        /// 
        public static void DeleteFile(string objectName)
        {
            var client = LocalOSSClient.OssClient;
            try
            {
                // 删除文件。
                client.DeleteObject(OssConfig.Bucket, objectName);
                Console.WriteLine("Delete object succeeded");
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Delete object failed. {0}", ex.Message));
            }
        }

        /// 
        /// 
        /// 
        /// 
        /// 设置为详细模式,返回所有删除的文件列表。
        public static void DeleteMultiFiles(List<string> files, bool quietMode = false)
        {
            var client = LocalOSSClient.OssClient;
            try
            {
                var request = new DeleteObjectsRequest(OssConfig.Bucket, files, quietMode);
                var result = client.DeleteObjects(request);
                if ((!quietMode) && (result.Keys != null))
                {
                    foreach (var obj in result.Keys)
                    {
                        Console.WriteLine(string.Format("Delete successfully : {0} ", obj.Key));
                    }
                }

                Console.WriteLine("Delete objects succeeded");
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Delete objects failed. {0}", ex.Message));
            }
        }

        public static bool ExistFile(string objectName)
        {
            bool exist = false;
            try
            {
                exist = LocalOSSClient.OssClient.DoesObjectExist(OssConfig.Bucket, objectName);
                Console.WriteLine("Object exist ? " + exist);
                return exist;
            }
            catch (OssException ex)
            {
                Console.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
                return exist;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
                return exist;
            }
        }
    }
}

你可能感兴趣的:(c#,阿里云,unity)