阿里云储存代码整理(由三卷天书整理)

最近不是很忙,就看了下阿里云储存,整理出来方法,为以后改版微笑话网内容多的时候用云储存准备,现在贴出来,希望对大家有所帮助,本文有博客园 三卷天书原创,转载请注明出处,谢谢!

直接贴代码了,就一个帮助类,直接调用里面的方法就OK了的,如果有什么地方出错,麻烦各位在回复区指出。

/// <summary>
    /// 阿里云储存帮助类(欢迎访问www.weixh.net微笑话,帮我涨点人气谢谢大家了)
    /// </summary>
    public class AliyunHelper
    {
        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 (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 (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 (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 (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion
    }

转载请注明出处。

posted @ 2015-12-18 14:19  三卷天书  阅读(1369)  评论(1编辑  收藏  举报