Net实现阿里云开放云存储服务(OSS)

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

2.第二步引用阿里成都程序集SDK 可以在NuGet搜索下载

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的配置

代码实现如下:

 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 的配置下

Controller 调用

  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:

 @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>

        }

此文为个人见解

时间: 2024-11-11 12:28:16

Net实现阿里云开放云存储服务(OSS)的相关文章

阿里云的NoSQL存储服务OTS的应用分析

这篇文章主要介绍了阿里云的NoSQL存储服务OTS的应用分析,OTS作为阿里巴巴开发的NoSQL存储技术服务现已面向用户商业化,需要的朋友可以参考下. 1. 概要  OTS是构建在阿里云飞天分布式系统上的NoSQL存储服务,提供海量结构化数据的存储和实时访问.OTS以实例和表来组织数据,通过自动的数据分区和负载均衡技术,对应用提供规模(数据和访问)的无缝扩展.应用通过调用OTS API/SDK或者操作管理控制台来使用OTS服务.OTS服务具有以下几个主要的特点:  规模可扩展:OTS具备可扩展的

腾讯云cos对象存储服务文件上传api就是一个大坑

一.介绍 对象存储服务(Cloud Object Service)是基于腾讯多年海量服务经验,对外提供的可靠.安全.易用的海量存储服务.提供多样化接入方式,以及全国部署的上传加速集群,可以无缝衔接CDN进行加速下载. 二.cos 文件上传api源码 /** * 单个文件上传,适用于小文件 * * @param bucketName * bucket名称 * @param remotePath * 远程文件路径 * @param localPath * 本地文件路径 * @return 服务器端返

开个坑, 写个阿里云开放储存服务(OSS)的C++版SDK以及客户端

这应该是继我研究手册QQ协议后的第2个稍微正式一点的网络程序, 不只是Scoket套接字编程, 还涉及到更多的HTTP协议知识! 阿里云开放储存服务OSS官方已经提供了不少SDK, 包括PHP/Python/Java/C#, ... 但唯独没有C/C++的, 很可惜. 不过, 论坛上倒是收集了不少C/C++版本的SDK. 但我还是想自己写一个试试, 于是就有了这个坑!!! 这个坑, 不是今天开的, 具体时间应该回到6号(今天10号), 不过我都不敢相信, 排除第3方代码, 已经有80多KB了啊!

从量子加密到机器学习,盘点2015阿里云开放的黑科技

http://www.csdn.net/article/2015-12-18/2826512 摘要:因为云计算应用的不断深入.以及对大数据处理需求的不断扩大,用户要求功能丰富.性能强大.高可用性的产品,云计算厂商们也推陈出新,不断地推出新产品,本文就盘点了业内翘楚阿里云在2015年那些有价值的新产品. 作为云计算产业热土的中国.2015年产业规模依然保持快速增长.且国内的公有云服务领域有几十家企业在角逐.经过几年的发展,眼下市场逐渐明朗.有些公有云企业已经遥遥率先,而有些企业非常可惜,已经開始掉

【初码干货】使用阿里云邮件推送服务架设自己邮件验证与推送体系

提示:阅读本文需提前了解的相关知识 1.电子邮件协议(http://baike.baidu.com/view/2367542.htm) 2.阿里云邮件推送(https://www.aliyun.com/product/directmail) 3.EDM(电子邮件营销)(http://baike.baidu.com/subview/1212416/8602812.htm) 4.SendCloud邮件服务(http://sendcloud.sohu.com/) 阅读目录结构 引: 一.需求分析 二.

腾讯云对象存储服务(cos)之PHP实践

云对象存储服务, BAT都有其业务, 本文选择腾讯是因为腾讯有每月免费流量, 而阿里和百度都是需要先付费后使用, 另外新兴的像七牛云存储, 也是很不错的解决方案. 贴代码 <?php /** * Simple Tencent COS SDK * 2016/05/09 * Author: hldh214 <[email protected]> */ // 配置项 start $appid = ''; $bucket_name = ''; $dir_name = ''; $secretID

一位云架构师用服务打动客户的故事之六(阿里云上的MSP最佳实践项目分享)

最近找了一个典型的云服务客户的案例对内进行分享,今天把核心内容脱敏后分享出来.希望能给目前在路上(做云服务MSP)的同行,有一些借鉴意义或者帮助. 该用户据全年跟进情况,目前该客户距正式启用我们公司云服务(运维服务)的日子已经有半年有余了,目前整体趋于稳定,故将目前用户进行深度复盘剖析,让各位伙伴更好的从该客户案例中提取一些有用的"武器"."售前技巧". 云产商:阿里云 企业背景-日企上来的终极三问~ > 为什么选择我们做云服务商?PS:此云服务并非指的是阿里

2018年视频云服务市场格局进入整合阶段,阿里云视频云位居市场竞争力领导者的位置

据计世资讯(CCW Research)的研究结果表明: 一.中国视频云市场进入高速发展阶段据计世资讯(CCW Research)的研究结果表明,近年来国内视频云市场保持了高速的增长势头,特别是2016年以来,视频云市场进入高速发展阶段,直播的火爆带动视频云服务需求快速增长.2018年中国视频云服务市场规模已经达到31.2亿元,同比增长36.2%.随着4K.VR等技术应用普及,将会催生出大量新的视频云应用场景.伴随着视频云深入行业发展,未来可以预见视频云市场将会拥有广阔的市场前景. 图表 1 20

阿里云邮件推送服务

提起邮件服务,最早之前一般自建邮件服务器,需要硬软件和运维的支持,稳定性也难保证,随着云服务的普及邮件推送功能的服务化是趋势,也省钱省事省心. 最早开始用过搜狐邮件服务,阿里云生态现在基本都出现了,我们来尝试一下阿里云的邮件推送服务: 一.阿里云控制台操作 首先在阿里云邮件推送控制台添加域名,然后在自己的dns服务器中添加如下的解析(根据控制台中的“配置”): 一个主机名为aliyundm的TXT记录,用于验证域名所有权 一个主机名为空.值为v=spf1 include:spf1.dm.aliy