在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)
{
}
}
}