亚马逊的私有云和自己搭的第三方S3协议使用 S3 sdk 上传文件 --闲来无聊记录下避免下次还得翻官方文档。复杂的应用看自己移步 api 官方文档 这里只是让你跑起来的基础教程
Endpoint == url
AccessKeySecret == 密钥
AccessKeyId == 用户
BucketName== 桶名称
private IAmazonS3 CreateClient()
{
IAmazonS3 client;
try
{
if (string.IsNullOrEmpty(S3Setting.Endpoint)
|| string.IsNullOrEmpty(S3Setting.AccessKeyId)
|| string.IsNullOrEmpty(S3Setting.AccessKeySecret))
{
throw new ArgumentNullException("S3Setting Endpoint、AccessKeyId、AccessKeyId为空");
}
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = S3Setting.Endpoint; // 私有环境。公网环境可以参考亚马逊官方
config.ForcePathStyle = true; //特别注意 要用寻址模式
LogManager.IntegrationLogger.Info($"config: 初始化成功");
client = new AmazonS3Client(S3Setting.AccessKeyId, S3Setting.AccessKeySecret, config);
}
catch (Exception ex)
{
LogManager.IntegrationLogger.Info($"创建IAmazonS3客户端异常:{ex} 配置信息:{S3Setting}");
throw ex;
}
return client;
}
public override void Save(string filePath, Stream inputStream)
{
if (string.IsNullOrEmpty(filePath) || inputStream == null || inputStream.Length == 0)
{
throw new ArgumentNullException("参数:filePath、inputStream为空");
}
var md5Hash = "";
using (Stream stream = new MemoryStream())
{
inputStream.CopyTo(stream);
inputStream.Position = 0;
stream.Position = 0;
using (var crypto = MD5.Create())
{
md5Hash = Convert.ToBase64String(crypto.ComputeHash(stream));
}
stream.Position = 0;
var request = new PutObjectRequest
{
BucketName = BucketName,
InputStream = stream,
Key = filePath,
ContentType = MimeMapping.GetMimeMapping(Path.GetFileName(filePath)),
MD5Digest = md5Hash, /// 这个值必须传不然服务端会校验数据一致性 导致获取的hash 和默认的hash 做比较 不一致报错
};
using (var s3client = CreateClient())
{
var response = s3client.PutObject(request);
if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception($"save emcs3 storage object failed. file:{filePath}, status:{response.HttpStatusCode}");
}
LogManager.IntegrationLogger.Info($"Save 文件 成功 : {request.Key}");
}
}
}