Net實現阿里雲開放雲存儲服務(OSS)

1 第一步框架搭建新建一個全新的MVC項目 (項目參考文檔https://docs.aliyun.com/?spm=5176.383663.9.6.5OJI07#/pub/oss/sdk/sdk-download&dotnet)html

2.第二步引用阿里成都程序集SDK 能夠在NuGet搜索下載app

 

3第三步代碼實現框架

 public class UploadFileHelper
    {
        public static OSSConfiguation _OssConfiguation;
        public static OssClient ossClient;
        public static string bucketName = "";
        public static string accessid = ""; // AccessID
        public static string accesskey = ""; // AccessKey
        public static string endpoint = "";
        public static string folder = "";
        public static string localPath = "";
        public static bool Islocal = false;
        public static string imgBucket = "";
        public static string pdfBucket = "";
        static UploadFileHelper()
        {
            _OssConfiguation = (OSSConfiguation)System.Configuration.ConfigurationManager.GetSection("OSSConfig");
            bucketName = _OssConfiguation.OssConfigService.imgBucket ==""
                ? _OssConfiguation.OssConfigService.pdfBucket
                : _OssConfiguation.OssConfigService.imgBucket;
            accessid = _OssConfiguation.OssConfigService.accessid;
            accesskey = _OssConfiguation.OssConfigService.accesskey;
            endpoint = _OssConfiguation.OssConfigService.endpoint;
            folder = _OssConfiguation.OssConfigService.folder;
            localPath = _OssConfiguation.OssConfigService.localPath;
            Islocal =Boolean.Parse(_OssConfiguation.OssConfigService.Islocal);

        }

        /// <summary>
        /// 上傳文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool UploadFile(HttpPostedFileBase file)
        {
            if (Islocal)
            {
                //本地存儲Local
                return UploadLocalFile(file);
            }
            else
            {
                //開放存儲OSS
                return UploadOSSFile(file);
            }
        }

        /// <summary>
        /// 上傳本地文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private static bool UploadLocalFile(HttpPostedFileBase file)
        {
            try
            {
                string newfilename = file.FileName;
                string serverTempFilePath = localPath + newfilename;
                file.SaveAs(serverTempFilePath);
                return true;

            }
            catch (Exception)
            {

                return false;
                throw;
            }
        }


        /// <summary>
        /// 上傳阿里雲文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private static bool UploadOSSFile(HttpPostedFileBase file)
        {
            try
            {
                ossClient = new OssClient(endpoint, accessid, accesskey); //固然這裏能夠封裝下

                var meta = new ObjectMetadata();

                meta.CacheControl = "max-age=315360000";

                meta.ContentType = ContentType((file.FileName).Substring(file.FileName.LastIndexOf(".")));

                var stream = file.InputStream;

                string name = folder + "/" + file.FileName;

                PutObjectResult result = ossClient.PutObject(bucketName, name, stream, meta);

                var fileinfo = ossClient.GetObject(bucketName, name);

                AccessControlList accs = ossClient.GetBucketAcl(bucketName);

                string imgurl = string.Empty;

                if (!accs.Grants.Any()) //判斷是否有讀取權限
                {
                    imgurl = ossClient.GeneratePresignedUri(bucketName, name, DateTime.Now.AddMinutes(5)).AbsoluteUri;
                    //生成一個簽名的Uri 有效期5分鐘
                }   
                else
                {

                    imgurl = string.Format("http://{0}.oss.aliyuncs.com/{1}", bucketName, name);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw new Exception(ex.Message);
            }

            //Response.Write(string.Format("<img src={0}>", imgurl));
        }





        /// <summary>
        /// 類型
        /// </summary>
        /// <param name="FilenameExtension"></param>
        /// <returns></returns>
        public static string ContentType(String FilenameExtension)
        {
            string type = "";
            if (FilenameExtension.Equals("BMP") || FilenameExtension.Equals("bmp"))
            {
                type = "image/bmp";
            }
            if (FilenameExtension.Equals("GIF") || FilenameExtension.Equals("gif"))
            {
                type = "image/gif";
            }
            if (FilenameExtension.Equals("JPEG") || FilenameExtension.Equals("jpeg") ||
                FilenameExtension.Equals("JPG") || FilenameExtension.Equals("jpg") ||
                FilenameExtension.Equals("PNG") || FilenameExtension.Equals("png"))
            {
                type = "image/jpeg";
            }
            if (FilenameExtension.Equals("HTML") || FilenameExtension.Equals("html"))
            {
                type = "text/html";
            }
            if (FilenameExtension.Equals("TXT") || FilenameExtension.Equals("txt"))
            {
                type = "text/plain";
            }
            if (FilenameExtension.Equals("VSD") || FilenameExtension.Equals("vsd"))
            {
                type = "application/vnd.visio";
            }
            if (FilenameExtension.Equals("PPTX") || FilenameExtension.Equals("pptx") ||
                FilenameExtension.Equals("PPT") || FilenameExtension.Equals("ppt"))
            {
                type = "application/vnd.ms-powerpoint";
            }
            if (FilenameExtension.Equals("DOCX") || FilenameExtension.Equals("docx") ||
                FilenameExtension.Equals("DOC") || FilenameExtension.Equals("doc"))
            {
                type = "application/msword";
            }
            if (FilenameExtension.Equals("XML") || FilenameExtension.Equals("xml"))
            {
                type = "text/xml";
            }
            if (FilenameExtension.Equals("PFD") || FilenameExtension.Equals("pdf"))
            {
                type = "application/pdf";
            }

            return type;
        }



        /// <summary>
        /// 建立模擬文件夾
        /// </summary>
        public static void CreateFolderName()
        {
            // 初始化OssClient
            ossClient = new OssClient(endpoint, accessid, accesskey);

            const string key = "yourfolder/";
            using (MemoryStream ms = new MemoryStream())
            {
                ossClient.PutObject(bucketName, key, ms);
            }
        }




        /// <summary>
        /// 獲取全部圖片
        /// </summary>
        public static OSSInfoListModel Bind()
        {
            var model = new OSSInfoListModel();
            ossClient = new OssClient(accessid, accesskey);
            var buck = ossClient.ListBuckets();
            var listing = ossClient.ListObjects(bucketName);
            model.Bucket = buck;
            model.ObjectListing = listing;
            return model;

        }


        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="bucketname"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Delete(string bucketname, string key)
        {
            try
            {
                ossClient = new OssClient(accessid, accesskey);
                ossClient.DeleteObject(bucketname, key);
                return true;

            }
            catch (Exception)
            {
                return false;
                throw;
            }

        }



        /// <summary>
        /// 新建Bucket
        /// </summary>
        /// <param name="bucketName"></param>
        /// <returns></returns>
        public static bool CreateBucket(string bucketName)
        {
            try
            {
                // 初始化OssClient
                ossClient = new OssClient(endpoint, accessid, accesskey);
                // 新建一個Bucket
                ossClient.CreateBucket(bucketName);
                return true;

            }
            catch (Exception)
            {
                return false;
                throw;
            }
        }

        /// <summary>
        /// 獲取全部的Bucket
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Bucket> GetAllBucket()
        {
            // 初始化OssClient
            ossClient = new OssClient(endpoint, accessid, accesskey);
            var buckets = ossClient.ListBuckets();
            return buckets;
        }

        /// <summary>
        /// 判斷Bucket是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool GetBucketBybucketName(string name)
        {
            // 初始化OssClient
            ossClient = new OssClient(endpoint, accessid, accesskey);
            var exist = ossClient.ListBuckets().Any(b => b.Name.Equals(name));
            return exist;
        }


        /// <summary>
        /// 刪除Bucket
        /// </summary>
        /// <param name="name"></param>
        public static bool DeleteBucket(string name)
        {
            try
            {
                // 初始化OssClient
                ossClient = new OssClient(endpoint, accessid, accesskey);
                ossClient.DeleteBucket(name);
                return true;

            }
            catch (Exception)
            {
                return false;
                throw;
            }
        }

        /// <summary>
        /// 使用CNAME進行訪問
        /// </summary>
        public static void UseCName(HttpPostedFileBase file)
        {
            // 好比你的域名"http://my-cname.com"CNAME指向你的bucket域名"mybucket.oss-cn-hangzhou.aliyuncs.com"
            ossClient = new OssClient("http://my-cname.com/", accessid, accesskey);
            var meta = new ObjectMetadata();
            meta.CacheControl = "max-age=315360000";
            meta.ContentType = ContentType((file.FileName).Substring(file.FileName.LastIndexOf(".")));
            var stream = file.InputStream;
            string name = "test" + "/" + file.FileName;
            PutObjectResult result = ossClient.PutObject(bucketName, name, stream, meta);
        }


        /// <summary>
        /// 建立文件夾
        /// </summary>
        public static void CreateFolder()
        {

            // 初始化OssClient
            var client = new OssClient(endpoint, accessid, accesskey);
            // Note: key treats as a folder and must end with a slash.
            const string key = "yourfolder/";
            // put object with zero bytes stream.
            using (MemoryStream ms = new MemoryStream())
            {
                client.PutObject(bucketName, key, ms);
            }
        }

    }

 

爲了更加易用我對一些基本參數進行了Web.Config的配置post

代碼實現以下:阿里雲

 public class OSSConfigHandler : IConfigurationSectionHandler
    {

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            if (section == null)

                throw new ArgumentNullException("section");

            OSSConfiguation config;

            if (parent != null)
            {

                var parentConfig = (OSSConfiguation) parent;

                config = (OSSConfiguation) ((ICloneable) parentConfig).Clone();

            }
            else
            {
                config = new OSSConfiguation();
            }

            var services = new OSSConfigService();

            for (int i = 0; i < section.ChildNodes.Count; i++)
            {
                try
                {
                    XmlNode element = section.ChildNodes.Item(i); 
                    if (element.NodeType == XmlNodeType.Comment) continue;
                    if (element.Name == "OssConfigService")
                    {
                       
                        var bucketName = element.Attributes["bucketName"] != null ? element.Attributes["bucketName"].Value : "";
                        var accessid = element.Attributes["accessid"] != null ? element.Attributes["accessid"].Value : "";
                        var accesskey = element.Attributes["accesskey"] != null ? element.Attributes["accesskey"].Value : "";
                        var endpoint = element.Attributes["endpoint"] != null ? element.Attributes["endpoint"].Value : "";
                        var folder = element.Attributes["folder"] != null ? element.Attributes["folder"].Value : "";
                        var Islocal = element.Attributes["Islocal"] != null ? element.Attributes["Islocal"].Value : "";
                        var localPath = element.Attributes["localPath"] != null ? element.Attributes["localPath"].Value : "";
                        var imgBucket = element.Attributes["imgBucket"] != null ? element.Attributes["imgBucket"].Value : "";
                        var pdfBucket = element.Attributes["pdfBucket"] != null ? element.Attributes["pdfBucket"].Value : "";

                        services.bucketName = bucketName;
                        services.accessid = accessid;
                        services.accesskey = accesskey;
                        services.endpoint = endpoint;
                        services.folder = folder;
                        services.Islocal = Islocal;
                        services.localPath = localPath;
                        services.imgBucket = imgBucket;
                        services.pdfBucket = pdfBucket;


                    }
                }
                catch (Exception exception)
                {

                }

            }

            config.OssConfigService = services;
            return config;
        }
    }
 /// <summary>
    /// 
    /// </summary>
    public class OSSConfigService
    {
        public OSSConfigService()
        {

        }


        /// <summary>
        /// 
        /// </summary>
        public string bucketName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string accessid { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string accesskey { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string endpoint { get; set; }

        /// <summary>
        /// 文件夾
        /// </summary>
        public string folder { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string  Islocal { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string localPath { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string imgBucket { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string pdfBucket { get; set; }

     

    }
public class OSSConfiguation : ICloneable
    {

        public OSSConfiguation()
        {
            OssConfigService = new OSSConfigService();
        }

        /// <summary>
        /// 
        /// </summary>
        public OSSConfigService OssConfigService { get; set; }

        public object Clone()
        {
            throw new NotImplementedException();
        }
    }

Web.Config 的配置下 url

 

 

Controller 調用spa

  public class HomeController : Controller
    {

        public HomeController()
        {

        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
           var model= UploadFileHelper.Bind();
           return View(model);
        }



        /// <summary>
        /// 上傳
        /// </summary>
        /// <returns></returns>
        public ActionResult FileSubmit()
        {
            var Picture = Request.Files[0];
            var PDF = Request.Files[1];
            bool s = false;
            var files = Request.Files;
            HttpPostedFileBase postedfile=null;
            for (int i = 0; i < files.Count; i++)
            {
                if (files[i].FileName.Length>0)
                {

                     postedfile = files[i];
                      s = UploadFileHelper.UploadFile(postedfile);
                }

            }

            if (s)
            {
                return Content("上傳成功");
            }
            else
            {
                return Content("上傳失敗");
            }
            
        }


        /// <summary>
        ///刪除
        /// </summary>
        /// <param name="key"></param>
        /// <param name="bucketname"></param>
        /// <returns></returns>
        public void  Delete(string key, string bucketname)
        {
            if(UploadFileHelper.Delete(bucketname, key))
            {
                  Response.Write("刪除成功");
              
            }
            else
            {
                Response.Write("刪除失敗");
            }
        }



      

        /// <summary>
        /// 列表Bucket
        /// </summary>
        /// <returns></returns>
        public ActionResult ListBucket()
        {
            var buckets1 = UploadFileHelper.GetAllBucket();
            return View(buckets1);
        }


        /// <summary>
        ///刪除Bucket
        /// </summary>
        /// <returns></returns>
        public void DeleteBucket(string bucketname)
        {
            if (UploadFileHelper.DeleteBucket(bucketname))
            {
                Response.Write("刪除成功");
            }
            else
            {
                Response.Write("刪除失敗");
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public void CreateBucket()
        {
            string name = Request.Form["bucketname"];
            if (UploadFileHelper.CreateBucket(name))
            {
                Response.Write("建立成功");
            }
            else
            {
                Response.Write("建立失敗");
            }
        }


    }

 

View:code

 @using (Html.BeginForm("FileSubmit", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
        {

            <input type="file" name="Picture" id="Picture" />
            <input type="file" name="PDF" id="PDF" />

            <button type="submit">上傳</button>

        }

此文爲我的看法orm

相關文章
相關標籤/搜索