90 lines
3.0 KiB
C#
90 lines
3.0 KiB
C#
using Aliyun.OSS;
|
|
using Aliyun.OSS.Common;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace XPrint.Production.Business.Tools
|
|
{
|
|
public class OssTool
|
|
{
|
|
private string accessKeyId = string.Empty;
|
|
private string accessKeySecret = string.Empty;
|
|
private string endpoint = string.Empty;
|
|
private OssClient? client = null;
|
|
public OssTool(string accessKeyId, string accessKeySecret, string endpoint)
|
|
{
|
|
this.accessKeyId = accessKeyId;
|
|
this.accessKeySecret = accessKeySecret;
|
|
this.endpoint = endpoint;
|
|
|
|
this.client = new OssClient(endpoint, accessKeyId, accessKeySecret);
|
|
}
|
|
|
|
public bool PutObject(string bucketName, string key, Stream dataStream, DateTime? expirationTime = null)
|
|
{
|
|
try
|
|
{
|
|
var metaData = new ObjectMetadata();
|
|
if (expirationTime != null)
|
|
{
|
|
metaData.ExpirationTime = expirationTime!.Value;// DateTime.Now.AddDays(30);//图片保留30天
|
|
}
|
|
var result = client?.PutObject(bucketName, key, dataStream, metaData);
|
|
if (result?.HttpStatusCode == HttpStatusCode.OK)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public void DeleteObject(string bucketName, string key)
|
|
{
|
|
try
|
|
{
|
|
client?.DeleteObject(bucketName, 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 void DeleteObjects(string bucketName, List<string> keys)
|
|
{
|
|
try
|
|
{
|
|
var requests = new DeleteObjectsRequest(bucketName, keys);
|
|
client?.DeleteObjects(requests);
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|