OSS上传文件(一)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

OSS上传⽂件(⼀)引⽤AliyunOSS.dll
封装⼀个AliyunOSS帮助类
public static class AliyunOSS {
static string accessKeyId = Config.AccessKeyId;
static string accessKeySecret = Config.AccessKeySecret;
static string endpoint = Config.Endpoint;
static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
static string fileToUpload = Config.FileToUpload;
static double Expiration = Config.Expiration;
public static void PutObjectFromFile(string bucketName, string key, string ContentType = "image/jpeg") {
try {
using (var content = File.Open(fileToUpload, FileMode.Open)) {
var metadata = new ObjectMetadata();
metadata.ContentLength = content.Length;
metadata.ContentType = ContentType;
client.PutObject(bucketName, key, content, metadata);
}
// Console.WriteLine("Put object:{0} succeeded", key);
}
catch (OssException ex) {
// Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
// ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex) {
// Console.WriteLine("Failed with error info: {0}", ex.Message);
}
}
public static void PutObject(string bucketName, string key, Stream content, ObjectMetadata metadata) {
try {
client.PutObject(bucketName, key, content, metadata);
}
catch (OssException ex) {
}
catch (Exception ex) {
}
}
public static void DeleteObject(string bucketName, string key)
{
try
{
client.DeleteObject(bucketName, key);
}
catch (OssException ex)
{
}
catch (Exception ex)
{
}
}
public static void PutObject(string bucketName, string key, Stream content)
{
try
{
client.PutObject(bucketName, key, content);
}
catch (OssException ex)
{
}
catch (Exception ex)
{
}
}
public static string PutLocalFileBySignedUrl(string bucketName, string key) {
OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try {
var request = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get);
request.Expiration = DateTime.Now.AddMinutes(Expiration);
return client.GeneratePresignedUri(request).AbsoluteUri;
}
catch (OssException ex) {
// Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", // ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
return null;
}
catch (Exception ex) {
// Console.WriteLine("Failed with error info: {0}", ex.Message);
return null;
}
}
public static bool DoesObjectExist(string bucketName, string key)
{
OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
int i = 0;
GoConn:
try
{
return client.DoesObjectExist(bucketName, key);
}
catch (OssException ex)
{
if (i < 3)
{
++i;
goto GoConn;
}
throw;
}
}
}。

相关文档
最新文档