背景:我们是公司内部搭建的存储 并不是使用公网云,可供参考
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 can