在webconfig中配置信息 <?xml version="1.0" encoding="utf-8"?><configuration><appSettings> <add key="AccessKey" value="你的key"/><add key="AccessKeySecret" valu ...
在webconfig中配置信息
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="AccessKey" value="你的key"/>
<add key="AccessKeySecret" value="你的秘鑰"/>
<add key="EndPointHangzhou" value="oss-cn-hangzhou.aliyuncs.com"/>
<add key="BucketName" value="webfile"/>
<add key="DomainImg" value="映射你的伺服器"/>
<add key="DomainFiles" value="映射你的伺服器"/>
</appSettings>
</configuration>
官方文檔:https://help.aliyun.com/document_detail/31947.html
public class AliyunOssHelper
{
private static string _accessKey;
private static string _accessKeySecret;
private static string _endPoint;
private static string _bucketName;
private static string _domainImag;
private static string _domainFile;
private OssClient ossClient;
private static bool _doesBucketExist;
private static readonly object _locker = new object();
public AliyunOssHelper()
{
try
{
_accessKey = ConfigHelper.AccessKey;
_accessKeySecret = ConfigHelper.AccessKeySecret;
_endPoint = ConfigHelper.EndPointHangzhou;
_bucketName = ConfigHelper.BucketNameFx110;
_domainImag = ConfigHelper.DomainImg;
_domainFile = ConfigHelper.DomainFiles;
ossClient = new OssClient(_endPoint, _accessKey, _accessKeySecret);
CheckbucketName(_bucketName);
}
catch (Exception ex)
{
}
}
/// <summary>
/// 上傳文件
/// </summary>
/// <param name="key"></param>
/// <param name="filename"></param>
/// <returns></returns>
public string UploadFile(String key, String filePath, short fileType)
{
try
{
FileStream ReadStream = File.Open(filePath, FileMode.Open);
ObjectMetadata objectMeta = new ObjectMetadata
{
//設置內容長度
ContentLength = ReadStream.Length
};
PutObjectResult result = ossClient.PutObject(_bucketName, key, ReadStream, objectMeta);
if (result.HttpStatusCode == HttpStatusCode.OK)
{
ReadStream.Close();
if(fileType == 4) { return GetFileUrl(key); }
return GetImgUrl(key);
}
ReadStream.Close();
return "上傳失敗";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 大文件上傳
/// </summary>
/// <param name="key"></param>
public String MutiPartUpload(string key, string filePath, short fileType)
{
try
{
InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(_bucketName, key);
InitiateMultipartUploadResult initResult = ossClient.InitiateMultipartUpload(initRequest);
// 設置每塊為 5M
int partSize = 1024 * 1024 * 5;
FileInfo partFile = new FileInfo(filePath);
// 計算分塊數目
int partCount = (int)(partFile.Length / partSize);
if (partFile.Length % partSize != 0)
{
partCount++;
}
// 新建一個List保存每個分塊上傳後的ETag和PartNumber
List<PartETag> partETags = new List<PartETag>();
for (int i = 0; i < partCount; i++)
{
// 獲取文件流
FileStream fis = new FileStream(partFile.FullName, FileMode.Open);
// 跳到每個分塊的開頭
long skipBytes = partSize * i;
fis.Position = skipBytes;
//fis.skip(skipBytes);
// 計算每個分塊的大小
long size = partSize < partFile.Length - skipBytes ?
partSize : partFile.Length - skipBytes;
// 創建UploadPartRequest,上傳分塊
UploadPartRequest uploadPartRequest = new UploadPartRequest(_bucketName, key, initResult.UploadId);
uploadPartRequest.InputStream = fis;
uploadPartRequest.PartSize = size;
uploadPartRequest.PartNumber = (i + 1);
UploadPartResult uploadPartResult = ossClient.UploadPart(uploadPartRequest);
// 將返回的PartETag保存到List中。
partETags.Add(uploadPartResult.PartETag);
// 關閉文件
fis.Close();
}
CompleteMultipartUploadRequest completeReq = new CompleteMultipartUploadRequest(_bucketName, key, initResult.UploadId);
foreach (PartETag partETag in partETags)
{
completeReq.PartETags.Add(partETag);
}
//完成分塊上傳
CompleteMultipartUploadResult completeResult = ossClient.CompleteMultipartUpload(completeReq);
//返回最終文件的MD5,用於用戶進行校驗
if (completeResult.HttpStatusCode == HttpStatusCode.OK)
{
//return completeResult.Location;
if (fileType == 4) { return GetFileUrl(key); }
return GetImgUrl(key);
}
return "上傳失敗";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 下載文件
/// </summary>
/// <param name="key"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public ObjectMetadata DownloadFile(String key, String filePath)
{
GetObjectRequest downloadRequest = new GetObjectRequest(_bucketName, key);
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
downloadRequest.SetRange(1000, 5000);
var result = ossClient.GetObject(downloadRequest, fs);
return result;
}
/// <summary>
/// 獲取Bucket列表
/// </summary>
/// <returns></returns>
public string GetBucketsList()
{
string result = "";
try
{
IEnumerable list = ossClient.ListBuckets();
foreach (Bucket bt in list)
{
result += string.Format("名稱:{0};創建日期:{1}", bt.Name, bt.CreationDate.ToString());
}
}
catch (OssException ex)
{
result = string.Format("創建失敗。錯誤代碼:{0}; 錯誤消息:{1}。\nRequestID:{2}\tHostID:{3}",
ex.ErrorCode,
ex.Message,
ex.RequestId,
ex.HostId);
}
return result;
}
/// <summary>
/// 獲取Bucket中的文件列表
/// </summary>
/// <param name="bucketName"></param>
/// <returns></returns>
public string GetObjectlist(string bucketName)
{
string result = "";
try
{
ObjectListing list = ossClient.ListObjects(bucketName);
IEnumerable<OssObjectSummary> objects = list.ObjectSummaries;
foreach (OssObjectSummary ob in objects)
{
if (ob.Key.LastIndexOf('/') != ob.Key.Length - 1)
result += string.Format("文件名:{0} 文件大小: {1}", ob.Key, GetSize(ob.Size));
}
}
catch (OssException ex)
{
result = string.Format("創建失敗。錯誤代碼:{0}; 錯誤消息:{1}。\nRequestID:{2}\tHostID:{3}",
ex.ErrorCode,
ex.Message,
ex.RequestId,
ex.HostId);
}
return result;
}
/// <summary>
/// 獲取文件大小
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
public string GetSize(long size)
{
if (size > 1024 * 1024)
return size / (1024 * 1024) + "." + (size % (1024 * 1024)) / 1024 + "MB";
else if (size > 1024)
return size / 1024 + "." + (size % 1024) / 10 + "KB";
else
return size + "位元組";
}
/// <summary>
/// 刪除一個Object
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string DeleteObject(string obj)
{
try
{
ossClient.DeleteObject(_bucketName, obj);
return string.Format("刪除成功!文件:" + obj);
}
catch (OssException ex)
{
return (string.Format("刪除失敗。錯誤代碼:{0}; 錯誤消息:{1}。\nRequestID:{2}\tHostID:{3}",
ex.ErrorCode,
ex.Message,
ex.RequestId,
ex.HostId));
}
}
/// <summary>
/// 刪除一個Bucket和其中的Objects
/// </summary>
public void DeleteBucket()
{
ObjectListing ol = ossClient.ListObjects(_bucketName);
List<OssObjectSummary> listDeletes = new List<OssObjectSummary>(ol.ObjectSummaries);
//listDeletes.AddRange(ol.ObjectSummaries);先構造後添加也可以
foreach (OssObjectSummary s in listDeletes)
{
//遍歷每個Bucket下ObjectName
String ObjectName = s.Key;
//刪除指定bucket下的Bucket下的ObjectName
ossClient.DeleteObject(_bucketName, ObjectName);
}
//刪除bucket
ossClient.DeleteBucket(_bucketName);
}
/// <summary>
/// 獲取url
/// </summary>
/// <param name="fullName"></param>
/// <returns></returns>
string GetImgUrl(string fullName)
{
if (string.IsNullOrWhiteSpace(_domainImag))
{
return $"http://{_bucketName}.{_endPoint}/{fullName}";
}
return _domainImag + "/" + fullName;
}
/// <summary>
/// 獲取文件url
/// </summary>
/// <param name="fullName"></param>
/// <returns></returns>
string GetFileUrl(string fullName)
{
if (string.IsNullOrWhiteSpace(_domainFile))
{
return $"http://{_bucketName}.{_endPoint}/{fullName}";
}
return _domainFile + "/" + fullName;
}
/// <summary>
/// 檢查buket存在
/// </summary>
/// <param name="bucketName"></param>
void CheckbucketName(String bucketName)
{
try
{
if (!_doesBucketExist && !ossClient.DoesBucketExist(bucketName))
{
lock (_locker)
{
if (!_doesBucketExist && !ossClient.DoesBucketExist(bucketName))
ossClient.CreateBucket(bucketName);
}
_doesBucketExist = true;
}
}
catch (Exception e)
{
}
}
}