【代码片段】阿里云储存帮助类

版权声明: https://blog.csdn.net/michelsn/article/details/80304731
using Aliyun.OSS;
using Aliyun.OSS.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.WebControls;

namespace QuickEAS.CoreLib.Aliyun
{
    /// <summary>阿里云储存帮助类</summary>
    public class LibAliyunHelper
    {
        const string accessKeyId = "<your access key id>";
        const string accessKeySecret = "<your access key secret>";
        const string endpoint = "<valid host name>";

        #region 上传部分
        /// <summary>
        /// 简单上传文件
        /// </summary>
        /// <param name="file">上传控件</param>
        /// <param name="key">文件标识</param>
        /// <param name="bucketName">空间名</param>
        public static string AliyunUploadFile(FileUpload file, string key, string bucketName)
        {
            try
            {
                Stream sr = file.PostedFile.InputStream;
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                var result = client.PutObject(bucketName, key, sr);
                return "succeeded";
            }
            catch (OssException ex)
            {
                return "上传失败:" + ex.ErrorCode;
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 简单上传文件
        /// </summary>
        /// <param name="file">上传控件</param>
        /// <param name="key">文件标识</param>
        /// <param name="bucketName">空间名</param>
        public static string AliyunUploadFile(HttpPostedFile file, string key, string bucketName)
        {
            try
            {
                Stream sr = file.InputStream;
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                var result = client.PutObject(bucketName, key, sr);
                return "succeeded";
            }
            catch (OssException ex)
            {
                return "上传失败:" + ex.ErrorCode;
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 分片上传
        /// </summary>
        /// <param name="bucketName">空间名</param>
        /// <param name="key">唯一标识</param>
        /// <param name="file">上传控件</param>
        /// <param name="partSize">每片大小(默认5MB)</param>
        /// <returns></returns>
        public static string AliyunUploadPart(string bucketName, string key, FileUpload file, int partSize = 5 * 1024 * 1024)
        {
            try
            {
                Stream sr = file.PostedFile.InputStream;
                OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                client.PutBigObject(bucketName, key, sr, null, partSize);
                return "succeeded";
            }
            catch (OssException ex)
            {
                return "上传失败:" + ex.ErrorCode;
            }
            catch (System.Exception ex)
            {
                return "上传失败:" + ex.Message;
            }

        }
        /// <summary>
        /// 分片上传
        /// </summary>
        /// <param name="bucketName">空间名</param>
        /// <param name="objectName">key</param>
        /// <param name="fileToUpload">指定分片上传文件路径</param>
        /// <param name="partSize">分片大小(单位:字节)</param>
        public static void UploadMultipart(String bucketName, String key, FileUpload file, int partSize = 5 * 1024 * 1024)
        {
            var uploadId = InitiateMultipartUpload(bucketName, key);
            var partETags = UploadParts(bucketName, key, file, uploadId, partSize);
            var completeResult = CompleteUploadPart(bucketName, key, uploadId, partETags);
            //Console.WriteLine(@"Upload multipart result : " + completeResult.Location);
        }

        private static string InitiateMultipartUpload(String bucketName, String objectName)
        {
            var request = new InitiateMultipartUploadRequest(bucketName, objectName);
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            var result = client.InitiateMultipartUpload(request);
            return result.UploadId;
        }
        private static List<PartETag> UploadParts(String bucketName, String objectName, FileUpload file, String uploadId, int partSize)
        {
            var fileSize = file.PostedFile.ContentLength;
            var partCount = fileSize / partSize;
            if (fileSize % partSize != 0)
            {
                partCount++;
            }

            var partETags = new List<PartETag>();
            using (var sr = file.PostedFile.InputStream)
            {
                for (var i = 0; i < partCount; i++)
                {
                    var skipBytes = (long)partSize * i;
                    sr.Seek(skipBytes, 0);
                    var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
                    var request = new UploadPartRequest(bucketName, objectName, uploadId)
                    {
                        InputStream = sr,
                        PartSize = size,
                        PartNumber = i + 1
                    };
                    OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                    var result = client.UploadPart(request);
                    partETags.Add(result.PartETag);
                }
            }
            return partETags;
        }
        private static CompleteMultipartUploadResult CompleteUploadPart(String bucketName, String objectName, String uploadId, List<PartETag> partETags)
        {
            var completeMultipartUploadRequest =
                new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
            foreach (var partETag in partETags)
            {
                completeMultipartUploadRequest.PartETags.Add(partETag);
            }
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            return client.CompleteMultipartUpload(completeMultipartUploadRequest);
        }
        #endregion

        #region URL访问
        /// <summary>
        /// URL获取
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetUrlGet(string bucketName, string key)
        {
            var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = new DateTime().AddHours(1)
            };
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            var uri = client.GeneratePresignedUri(req);
            return uri.ToString();
        }
        /// <summary>
        /// URL获取
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="key"></param>
        /// <param name="timeMinutes">过期时间(分)</param>
        /// <returns></returns>
        public static string GetUrlGet(string bucketName, string key, int timeMinutes)
        {
            var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = new DateTime().AddMinutes(timeMinutes)
            };
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            var uri = client.GeneratePresignedUri(req);
            return uri.ToString();
        }
        #endregion

        #region 文件下载
        /// <summary>
        /// 从指定的OSS存储空间中获取指定的文件
        /// </summary>
        /// <param name="bucketName">要获取的文件所在的存储空间的名称</param>
        /// <param name="key">要获取的文件的名称</param>
        /// <param name="fileToDownload">文件保存的本地路径</param>
        public static string GetObject(string bucketName, string key, string fileToDownload)
        {
            try
            {
                // 初始化OssClient
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                var obj = client.GetObject(bucketName, key);
                using (var requestStream = obj.Content)
                {
                    byte[] buf = new byte[1024];
                    var fs = File.Open(fileToDownload, FileMode.OpenOrCreate);
                    var len = 0;
                    while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                    {
                        fs.Write(buf, 0, len);
                    }
                    fs.Close();
                }

                return "succeeded";
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

    }
}

阅读更多

扫码向博主提问

SZ大伟

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • C#.NET
  • 架构设计
  • 跨境电商
  • DELPHI
  • ERP
去开通我的Chat快问
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页