using Amazon.S3;
using Amazon.S3.Model;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
namespace Zowie.Common.Helper
{
/// <summary>
/// 天翼云OSS
/// NuGet引用AWSSDK.Core、AWSSDK.S3,版本:3.7.304.3、3.7.308.2
/// </summary>
public class TYiYunHelper
{
private AmazonS3Client client;
public TYiYunHelper()
{
var accessKey = "AccessKey";
var secretKey = "SecretKey";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate (
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors) // 自签名忽略认证
{
return true;
};
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "Endpoint"; // 指定IP和Port
config.ForcePathStyle = true; // 使用路径模式
config.SignatureVersion = "2"; // 签名版本
client = new AmazonS3Client(accessKey, secretKey, config); // 建立连接
}
// 创建一个存储桶
public async Task CreateBucket(string? bucketName = null)
{
try
{
if (string.IsNullOrEmpty(bucketName)) return;
PutBucketRequest request = new PutBucketRequest();
// 创建存储空间。
request.BucketName = bucketName;
// 设置存储空间的读写权限为公共读。
request.CannedACL = S3CannedACL.PublicRead;
PutBucketResponse response = await client.PutBucketAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 上传
/// </summary>
/// <param name="bucketName">填写Bucket名称,例如examplebucket</param>
/// <param name="key">相对路径,相对路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。</param>
/// <param name="filepath">绝对路径,例如D:\\localpath\\examplefile.txt</param>
/// <returns></returns>
public async Task<bool> UploadFile(string bucketName, string key, string filepath)
{
try
{
if (key.StartsWith('/'))
{
key = key.Substring(1);
}
string pattern = @"\\|/";
string replacement = @"/";
Regex rgx = new Regex(pattern);
filepath = rgx.Replace(filepath, replacement);
key = rgx.Replace(key, replacement);
// 上传文件。
var request = new PutObjectRequest();
request.BucketName = bucketName;
request.Key = key;
request.CannedACL = S3CannedACL.PublicRead;
request.FilePath = filepath;
if (key.ToLower().EndsWith(".png"))
{
request.ContentType = "image/png";
}
else if (key.ToLower().EndsWith(".jpg") || key.ToLower().EndsWith(".jpeg"))
{
request.ContentType = "image/jpeg";
}
else if (key.ToLower().EndsWith(".gif"))
{
request.ContentType = "image/gif";
}
else if (key.ToLower().EndsWith(".mp4"))
{
request.ContentType = "video/mp4";
}
var result = await client.PutObjectAsync(request);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 存储一个字符串
/// </summary>
/// <param name="bucketName">填写Bucket名称,例如examplebucket</param>
/// <param name="key">相对路径,相对路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。</param>
/// <param name="inputStream">字符内容</param>
/// <returns></returns>
public async Task<bool> PutString(string bucketName, string key, Stream inputStream)
{
try
{
if (key.StartsWith('/'))
{
key = key.Substring(1);
}
string pattern = @"\\|/";
string replacement = @"/";
Regex rgx = new Regex(pattern);
// 上传文件。
var request = new PutObjectRequest();
request.BucketName = bucketName;
request.Key = key;
request.CannedACL = S3CannedACL.PublicRead;
request.InputStream = inputStream;
if (key.ToLower().EndsWith(".png"))
{
request.ContentType = "image/png";
}
else if (key.ToLower().EndsWith(".jpg") || key.ToLower().EndsWith(".jpeg"))
{
request.ContentType = "image/jpeg";
}
else if (key.ToLower().EndsWith(".gif"))
{
request.ContentType = "image/gif";
}
else if (key.ToLower().EndsWith(".mp4"))
{
request.ContentType = "video/mp4";
}
var result = await client.PutObjectAsync(request);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="bucketName">桶名</param>
/// <param name="key">相对路径,相对路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。</param>
/// <returns></returns>
public async Task<bool> DeleteObject(string bucketName, string key)
{
try
{
// 删除文件。
var request = new DeleteObjectRequest();
if (key.StartsWith('/'))
{
key = key.Substring(1);
}
request.BucketName = bucketName;
request.Key = key;
request.BypassGovernanceRetention = true;
DeleteObjectResponse response = await client.DeleteObjectAsync(request);
}
catch (Exception ex)
{
throw ex;
}
return true;
}
/// <summary>
/// 批量删除文件
/// </summary>
/// <param name="bucketName">桶名</param>
/// <param name="objectNames">相对路径,相对路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。</param>
/// <returns></returns>
public async Task<bool> DeleteObjects(string bucketName, List<string> objectNames)
{
try
{
var request = new DeleteObjectsRequest();
request.BucketName = bucketName;
request.Quiet = false;
foreach (var item in objectNames)
{
request.AddKey(item);
}
request.BypassGovernanceRetention = true;
DeleteObjectsResponse response = await client.DeleteObjectsAsync(request);
}
catch (Exception ex)
{
throw ex;
}
return true;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="bucketName">桶名</param>
/// <param name="key">相对路径,相对路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。</param>
/// <param name="filepath">填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt</param>
/// <returns></returns>
public async Task GetObject(string bucketName, string key, string filepath)
{
try
{
if (key.StartsWith('/'))
{
key = key.Substring(1);
}
string pattern = @"\\|/";
string replacement = @"/";
Regex rgx = new Regex(pattern);
filepath = rgx.Replace(filepath, replacement);
// 下载文件到流。OssObject包含了文件的各种信息,如文件所在的存储空间、文件名、元信息以及一个输入流。
var obj = await client.GetObjectAsync(bucketName, key);
using (Stream requestStream = obj.ResponseStream)
{
byte[] buf = new byte[1024];
// 确保本地目录结构存在
string path = Path.GetDirectoryName(filepath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var fs = System.IO.File.Open(filepath, FileMode.OpenOrCreate);
var len = 0;
// 通过输入流将文件的内容读取到文件或者内存中。
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 文件是否存在
/// </summary>
/// <param name="bucketName"></param>
/// <param name="key"></param>
/// <returns></returns>
public async Task<bool> FileExist(string bucketName, string key)
{
try
{
if (key.StartsWith('/'))
{
key = key.Substring(1);
}
var obj = await client.GetObjectAsync(bucketName, key);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
.netcore 通过天翼云上传文件到存储桶中
最新推荐文章于 2024-07-24 18:49:07 发布