using Aliyun.OSS;
using System.Text.RegularExpressions;
namespace Zowie.Common.Helper
{
/// <summary>
/// 阿里云OSS
/// NuGet引用Aliyun.OSS.SDK.NetCore,版本:2.13.0
/// </summary>
public class ALiYunHelper
{
private OssClient client;
public ALiYunHelper()
{
var endpoint = "Endpoint";
var accessKey = "AccessKey";
var secretKey = "SecretKey";
client = new OssClient(endpoint, accessKey, secretKey);
}
// 创建一个存储桶
public string CreateBucket(string? bucketName = null)
{
try
{
// 创建存储空间。
var bucket = client.CreateBucket(bucketName);
// 设置存储空间的读写权限为公共读。
client.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);
return ("Create bucket succeeded, " + bucket.Name);
}
catch (Exception ex)
{
return ("Create bucket failed, " + ex.Message);
}
}
/// <summary>
/// 判断存储空间是否存在,不存在就创建,存在bug,未找到判断存储桶是否存在逻辑,这里如果目录里包含也会返回true
/// </summary>
/// <param name="bucketName">桶名</param>
public void DoesBucketExist(string bucketName)
{
try
{
var exist = client.DoesBucketExist(bucketName);
if (!exist)
{
CreateBucket(bucketName);
}
}
catch (Exception ex)
{
return;
}
}
/// <summary>
/// 上传
/// </summary>
/// <param name="bucketName">填写Bucket名称,例如examplebucket</param>
/// <param name="objectName">相对路径,相对路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。</param>
/// <param name="localFilename">绝对路径,例如D:\\localpath\\examplefile.txt</param>
/// <returns></returns>
public bool UploadFile(string bucketName, string objectName, string localFilename)
{
//objectName = "shouji/chongqing/rongchang/2023/10/17/202310171501034B62CC.jpg";
// 填写本地文件完整路径,例如D:\\localpath\\examplefile.txt。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
//localFilename = "C:/Users/Zowie/Desktop/1.png";
try
{
if (objectName.StartsWith('/'))
{
objectName = objectName.Substring(1);
.netcore 通过阿里云上传文件到存储桶中
于 2024-05-22 17:51:43 首次发布