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;
}
}
}

 

posted @ 2019-09-30 17:14  艺洁  阅读(2786)  评论(0编辑  收藏  举报