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()).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 = ; 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[];
var PDF = Request.Files[];
bool s = false;
var files = Request.Files;
HttpPostedFileBase postedfile=null;
for (int i = ; i < files.Count; i++)
{
if (files[i].FileName.Length>)
{ 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> }
此文为个人见解
Net实现阿里云开放云存储服务(OSS)的更多相关文章
- 阿里云的NoSQL存储服务OTS的应用分析
这篇文章主要介绍了阿里云的NoSQL存储服务OTS的应用分析,OTS作为阿里巴巴开发的NoSQL存储技术服务现已面向用户商业化,需要的朋友可以参考下. 1. 概要 OTS是构建在阿里云飞天分布式系统 ...
- 腾讯云开放云压测“黑科技“,产品上线从此不再“压力山大"
商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. 能否解决"高并发"问题一直是检验一个产品后台是否稳定,架构是否合理,性能是否强大的核心标准.对于产品而言,多高的并发 ...
- 如何利用京东云的对象存储(OSS)上传下载文件
作者:刘冀 在公有云厂商里都有对象存储,京东云也不例外,而且也兼容S3的标准因此可以利用相关的工具去上传下载文件,本文主要记录一下利用CloudBerry Explorer for Amazon S3 ...
- 对象存储服务 OSS(Object Storage Service),知识点(待补充上仓库代码)
资料 网址 官方文档 https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.3.1.3e1459669xRokl OSS Brow ...
- 基于PHP实现阿里云开放存储服务
开放存储服务(OpenStorageService,简称OSS),是阿里云对外提供的海量,安全,低成本,高可靠的云存储服务.用户可以通过简单的API(REST方式的接口),在任何时间.任何地点.任何互 ...
- 阿里云对象存储服务,OSS使用经验总结,图片存储,分页查询
阿里云OSS-使用经验总结,存储,账号-权限,分页,缩略图,账号切换 最近项目中,需要使用云存储,最后选择了阿里云-对象存储服务OSS.总的来说,比较简单,但是仍然遇到了几个问题,需要总结下. 1.O ...
- Go操作腾讯云COS对象存储的简单使用案例
准备环境 安装Go环境 Golang:用于下载和安装 Go 编译运行环境,请前往 Golang 官网进行下载 安装SDK go get -u github.com/tencentyun/cos-go- ...
- 阿里云之OSS 开放存储服务开发笔记
在使用云服务以后,你不用考虑他是否能承受压力,而是费用.不要考虑是否被攻击,而是他的API实现.本人开发阿里云服务也走了些崎岖之路,写下以备忘之. 阿里云的开放存储服务可以提供文件的存储服务,开放了上 ...
- .Net程序测试阿里云OSS开放存储服务
阿里云官网有提供OSS相关的操作API文档和.Net程序的 SDK,也可以在这里下载OSS相关文件 但是API文档里面的都是通过http请求和响应的消息来描述如何操作OSS的 而一般在程序中需要的是O ...
随机推荐
- vs2010怎么更改调试时使用的浏览器
在当前网站的起始网页上右击,在右击菜单中选择 浏览方式 步骤阅读 2
- How to receive a million packets per second
Last week during a casual conversation I overheard a colleague saying: "The Linux network stack ...
- 014 Mui
一:概述 1.说明 是开发出来的一套好用的代码片段 任何项目都可以使用MUI 官网:https://dev.dcloud.net.cn/mui/ 不能使用npm进行下载,需要手动从git上下载 2.下 ...
- Scrapy的 Shell终端
crapy Shell Scrapy终端是一个交互终端,我们可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看他们的工作方式,方便我们爬取的网页中提取的数据. ...
- QC9.2登陆时显示一个X号
这个是因为浏览器安全设置的问题,具体解决步骤如下: 进入“工具-Internet选项”设置窗口,进入“高级”选项卡,将“安全”设置中的“启用内存保护减少联机攻击”选项的勾选去掉,然后应用并确定.重启浏 ...
- FineReport简单上手
一.简介 FineReport是一个企业级报表制作.分析和展示工具 官网可以下载个人版进行体验学习:(windows版本设计器) https://www.finereport.com/product/ ...
- redis-cli中文乱码
在开发过程中,需要验证redis缓存中的数据,发现redis存储的中文全是乱码,因为默认情况下redis不转义中文.如果在平常开发中想要看到中文内容,可以在使用redis-cli 命令登陆redis服 ...
- unittest===unittest 的几种执行方式
#demo.py import requests import json class RunMain: def __init__(self, url, method, data=None): self ...
- SDKMAN一个基于命令行界面的SDK用户环境管理程序
1.背景 使用过Python开发的朋友,应该了解到Python2和Python3语法的差异,有时候从网上下载了基于不同解释器的代码,要来回切换版本, 使用起来不是很方便,有时候甚至很麻烦.于是有人发明 ...
- SonarQube + Jenkins代码审查环境安装文档 v1.2
1. 安装SonarQube 1.1. 下载 下载地址:https://www.sonarqube.org/downloads/ 本次使用安装包为:sonarqube-7.4.zip 需要提前准备jd ...