背景:我们是公司内部搭建的存储 并不是使用公网云,可供参考
1、Nuget包 AWSSDK.S3
2、创建一个单利模式 操作类
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace H3C.AtendanceService.Common
{
public class AWSS3Helper
{
private static AmazonS3Client _s3Client = null;
private static readonly object _locker = new object();
private static readonly string _accessKey = "s3的acesskey";
private static readonly string _secretKey = "s3的secretKey";
private static readonly string _s3url = "S3的host地址";//要带HTTP或者HTTPS
private static AWSS3Helper _instance = null;
private AWSS3Helper()
{
}
/// <summary>
/// 初始化
/// </summary>
/// <returns></returns>
public static AWSS3Helper GetInStance()
{
if (_instance == null)
lock (_locker)
if (_instance == null)
{
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = _s3url;
config.UseHttp = true;//根据实际情况
config.ForcePathStyle = true;
_s3Client = new AmazonS3Client(
_accessKey,
_secretKey,
config
);
_instance = new AWSS3Helper();
}
return _instance;
}
/// <summary>
/// 创建Bucket
/// </summary>
/// <param name="bucketName">bucketName</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<bool> CreateBucketAsync(string bucketName, CancellationToken cancellationToken = default)
{
if (await CheckBucketExistAsync(bucketName, cancellationToken)) return true;
var buckectres = await _s3Client.PutBucketAsync(bucketName);
if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
return false;
}
/// <summary>
/// 创建Bucket
/// </summary>
/// <param name="bucketName">bucketName</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public bool CreateBucket(string bucketName)
{
if (CheckBucketExist(bucketName)) return true;
var buckectres = _s3Client.PutBucket(bucketName);
if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
return false;
}
/// <summary>
/// 删除Bucket
/// </summary>
/// <param name="bucketName">bucketName</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<bool> DeleteBucketAsync(string bucketName, CancellationToken cancellationToken = default)
{
if (!(await CheckBucketExistAsync(bucketName, cancellationToken))) return true;
var buckectres = await _s3Client.DeleteBucketAsync(bucketName, cancellationToken);
if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
return false;
}
/// <summary>
/// 删除Bucket
/// </summary>
/// <param name="bucketName">bucketName</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public bool DeleteBucket(string bucketName)
{
if (!CheckBucketExist(bucketName)) return true;
var buckectres = _s3Client.DeleteBucket(bucketName);
if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
return false;
}
/// <summary>
/// 检测BucketName是否存在
/// </summary>
/// <param name="bucketName">bucketName</param>
/// <param name="cancellationToken">线程取消</param>
/// <returns></returns>
public async Task<bool> CheckBucketExistAsync(string bucketName, CancellationToken cancellationToken = default)
{
var response = await _s3Client?.ListBucketsAsync(cancellationToken);
if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK && response?.Buckets?.Count > 0)
return response.Buckets.Any(x => x.BucketName == bucketName);
return false;
}
/// <summary>
/// 检测BucketName是否存在
/// </summary>
/// <param name="bucketName">bucketName</param>
/// <returns></returns>
public bool CheckBucketExist(string bucketName)
{
var response = _s3Client?.ListBuckets();
if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK && response?.Buckets?.Count > 0)
return response.Buckets.Any(x => x.BucketName == bucketName);
return false;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="filepath">文件绝对路径</param>
/// <param name="bucketname">bucketname</param>
/// <param name="filename">唯一键值:命名</param>
/// <param name="dir">目录:目录名/目录名</param>
/// <param name="isDeletedSourceFile">是否删除源文件</param>
/// <param name="cancellationToken">线程取消</param>
/// <returns></returns>
public async Task<bool> UploadFileAsync(string filepath, string bucketname, string filename, string dir = "", bool isDeletedSourceFile = false, CancellationToken cancellationToken = default)
{
string key = filename;
if (!string.IsNullOrEmpty(dir))
{
dir = dir.EndsWith("/") ? dir : dir + "/";
dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
key = dir + filename;
}
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucketname,
Key = key,
FilePath = filepath,
CannedACL = S3CannedACL.PublicReadWrite //根据实际情况
};
PutObjectResponse response = await _s3Client.PutObjectAsync(request, cancellationToken);
if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
if (isDeletedSourceFile) File.Delete(filepath);
return true;
}
return false;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="filepath">文件绝对路径</param>
/// <param name="bucketname">bucketname</param>
/// <param name="filename">唯一键值:命名</param>
/// <param name="dir">目录:目录名/目录名</param>
/// <param name="isDeletedSourceFile">是否删除源文件</param>
/// <returns></returns>
public bool UploadFile(string filepath, string bucketname,string filename, string dir = "", bool isDeletedSourceFile = false)
{
string key = filename;
if (!string.IsNullOrEmpty(dir))
{
dir = dir.EndsWith("/") ? dir : dir + "/";
dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
key = dir + filename;
}
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucketname,
Key = key,
FilePath = filepath,
CannedACL = S3CannedACL.PublicReadWrite//根据实际情况
};
PutObjectResponse response = _s3Client.PutObject(request);
if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
if (isDeletedSourceFile) File.Delete(filepath);
return true;
}
return false;
}
/// <summary>
/// 上传文件,返回URL
/// </summary>
/// <param name="filepath">文件绝对路径</param>
/// <param name="bucketname">bucketname</param>
/// <param name="expiretime">失效时间</param>
/// <param name="filename">唯一键值:命名</param>
/// <param name="dir">目录:目录名/目录名</param>
/// <param name="isDeletedSourceFile">是否删除源文件</param>
/// <param name="cancellationToken">线程取消</param>
/// <returns>URL</returns>
public async Task<string> UploadFileReturnUrlAsync(string filepath, string bucketname, DateTime expiretime, string filename, string dir = "", bool isDeletedSourceFile = false, CancellationToken cancellationToken = default)
{
try
{
string key = filename;
if (!string.IsNullOrEmpty(dir))
{
dir = dir.EndsWith("/") ? dir : dir + "/";
dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
key = dir + filename;
}
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucketname,
Key = key,
FilePath = filepath,
CannedACL = S3CannedACL.PublicReadWrite//根据实际情况
};
PutObjectResponse response = await _s3Client.PutObjectAsync(request, cancellationToken);
if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
//return GetFileUrl(bucketname, key, expiretime);
var url = await GetFileUrlAsync(bucketname, key, expiretime);
if (!string.IsNullOrEmpty(url) && isDeletedSourceFile)
{
File.Delete(filepath);
return url;
}
}
return "";
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// 上传文件,返回URL
/// </summary>
/// <param name="filepath">文件绝对路径</param>
/// <param name="bucketname">bucketname</param>
/// <param name="expiretime">失效时间</param>
/// <param name="filename">唯一键值:命名</param>
/// <param name="dir">目录:目录名/目录名</param>
/// <param name="isDeletedSourceFile">是否删除源文件</param>
/// <param name="cancellationToken">线程取消</param>
/// <returns>URL</returns>
public string UploadFileReturnUrl(string filepath, string bucketname, DateTime expiretime, string filename, string dir = "", bool isDeletedSourceFile = false)
{
string key = filename;
if (!string.IsNullOrEmpty(dir))
{
dir = dir.EndsWith("/") ? dir : dir + "/";
dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
key = dir + filename;
}
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucketname,
Key = key,
FilePath = filepath,
CannedACL = S3CannedACL.PublicReadWrite//根据实际情况
};
PutObjectResponse response = _s3Client.PutObject(request);
if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
//return GetFileUrl(bucketname, key, expiretime);
var url = GetFileUrl(bucketname, key, expiretime);
if (!string.IsNullOrEmpty(url) && isDeletedSourceFile)
{
File.Delete(filepath);
return url;
}
}
return "";
}
/// <summary>
/// 根据key获取URL
/// </summary>
/// <param name="bucketname">bucketname</param>
/// <param name="key">唯一键值</param>
/// <param name="expiretime">失效时间</param>
/// <returns></returns>
public async Task<string> GetFileUrlAsync(string bucketname, string key, DateTime expiretime)
{
GetPreSignedUrlRequest urlRequest = new GetPreSignedUrlRequest
{
BucketName = bucketname,
Key = key,
Protocol = Protocol.HTTP,
Expires = expiretime
};
return await Task.Run(() => { return _s3Client.GetPreSignedURL(urlRequest); });
}
/// <summary>
/// 根据key获取URL
/// </summary>
/// <param name="bucketname">bucketname</param>
/// <param name="key">唯一键值</param>
/// <param name="expiretime">失效时间</param>
/// <returns></returns>
public string GetFileUrl(string bucketname, string key, DateTime expiretime)
{
GetPreSignedUrlRequest urlRequest = new GetPreSignedUrlRequest
{
BucketName = bucketname,
Key = key,
Protocol = Protocol.HTTP,
Expires = expiretime
};
return _s3Client.GetPreSignedURL(urlRequest);
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="bucketname">bucketname</param>
/// <param name="key">唯一键值</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<bool> DeleteFileAsync(string bucketname, string key, CancellationToken cancellationToken = default)
{
DeleteObjectRequest delete = new DeleteObjectRequest
{
BucketName = bucketname,
Key = key
};
var deleteObjectResponse = await _s3Client.DeleteObjectAsync(delete, cancellationToken);
if (deleteObjectResponse?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
return false;
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="bucketname">bucketname</param>
/// <param name="key">唯一键值</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public bool DeleteFile(string bucketname, string key)
{
DeleteObjectRequest delete = new DeleteObjectRequest
{
BucketName = bucketname,
Key = key
};
var deleteObjectResponse = _s3Client.DeleteObject(delete);
if (deleteObjectResponse?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
return false;
}
}
}
3、使用
//创建bucket
await AWSS3Helper.GetInStance().CreateBucketAsync("TestBucket");
//
await AWSS3Helper.GetInStance().UploadFileReturnUrlAsync("", buckname, DateTime.Now.AddYears(20), filename, "Dir/", true);