概述
由于云技术的日益成熟,越来越多的公司存储文件时会用到云技术,而亚马逊就提供了一个日益成熟的云环境的服务器群方便存储的文件。
Amazon Simple Storage Service (Amazon S3) 是一种对象存储服务,提供行业领先的可扩展性、数据可用性、安全性和性能。这意味着各种规模和行业的客户都可以使用 S3 来存储并保护各种用例(如数据湖、网站、移动应用程序、备份和还原、存档、企业应用程序、IoT 设备和大数据分析)的数据,容量不限。Amazon S3 提供了易于使用的管理功能,因此您可以组织数据并配置精细调整过的使用权限控制,从而满足特定的业务、组织和合规性要求。Amazon S3 可达到 99.999999999%(11 个 9)的持久性,并为全球各地的公司存储数百万个应用程序的数据。
下面介绍下在net环境下如何实现文件上传到AWS.
主要实现方式
1、定义接口IRemoteFile。
public interface IRemoteFile
{
string Upload(string sourceFile, string relativePath, string bucketName = null);
bool Delete(string url);
Stream Download(string relativePath, string bucketName);
long ComputeSize(string relativePath, string[] excludeKeywords);
}
2、实现方法,例如上传Upload方法。
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private static IAmazonS3 client;
private string _bucketName = MvcTools.GetAppSetting("AmazonS3Bucket");
public string Upload(string sourceFile, string relativePath, string bucketName = null)
{
if (bucketName != null)
{
_bucketName = bucketName;
}
else
{
_bucketName = MvcTools.GetAppSetting("AmazonS3Bucket");
}
string resultUrl = string.Empty;
bool success = false;
using (client = new AmazonS3Client())
{
try
{
PutObjectResponse putObjectResponse = client.PutObject(new PutObjectRequest
{
BucketName = _bucketName,
FilePath = sourceFile,
Grants = new List<S3Grant>() {
new S3Grant()
{
Permission = S3Permission.READ,
Grantee = new S3Grantee { URI = "http://acs.amazonaws.com/groups/global/AllUsers" }
}
},
Key = relativePath,
});
success = putObjectResponse.HttpStatusCode == System.Net.HttpStatusCode.OK;
if (!success)
{
logger.Error(putObjectResponse.ToJsonStri