最近需要每天同步內網的數據到外網的服務器上,用了幾天CyberDuck覺得經常忘記同步,故研究了一下亞馬遜S3的接口,寫了個定時上傳文件的服務。
附上代碼:
public string UploadFile()
{
String accessKeyID = "****";
String secretKey = "*****";
String bucketName = "根文件夾名";
String s3Path = "子文件夾名/文件名";
AWSCredentials credentials;
credentials = new BasicAWSCredentials(accessKeyID, secretKey);
AmazonS3Client s3Client = new AmazonS3Client(accessKeyID, secretKey, Amazon.RegionEndpoint.USEast1);
if (!CheckBucketExists(s3Client, bucketName))
{
s3Client.PutBucket(bucketName);
}
string localPath = "本地文件地址";
PutObjectRequest obj = new PutObjectRequest();
var fileStream = new FileStream(localPath, FileMode.Open, FileAccess.Read);
obj.InputStream = fileStream;
obj.BucketName = bucketName;
obj.Key = s3Path;
obj.CannedACL = S3CannedACL.PublicRead;
// 默認添加public權限
s3Client.PutObject(obj);
return “success”;
}
public static bool CheckBucketExists (AmazonS3Client s3, String bucketName) {
List<S3Bucket> buckets = s3.ListBuckets().Buckets;
foreach(S3Bucket bucket in buckets){
if (bucket.BucketName == bucketName) {
return true;
}
}
return false;
}