하이 레벨 .NET TransferUtility 클래스로 디렉터리 업로드
하이 레벨 .NET TransferUtility 클래스로 디렉터리 업로드 (Uploading a directory using the high-level .NET TransferUtility class)
TransferUtility 클래스를 사용해 전체 디렉터리를 업로드할 수 있어요. 기본적으로 API는 지정된 디렉터리의 루트에 있는 파일만 업로드해요. 다만 모든 하위 디렉터리의 파일을 재귀적으로 업로드하도록 지정할 수 있어요.
출처: 문서
본문
필터링 기준에 따라 지정된 디렉터리에서 파일을 선택하려면 필터링 표현식을 지정해요. 예를 들어 디렉터리에서 PDF 파일만 업로드하려면 "*.pdf" 필터 표현식을 지정해요.
디렉터리에서 파일을 업로드할 때는 결과 객체의 키 이름을 지정하지 않아요. Amazon S3는 원래 파일 경로를 사용해 키 이름을 구성해요. 예를 들어 다음 구조의 c:\myfolder라는 디렉터리가 있다고 가정해 보세요.
예시
C:\myfolder
\a.txt
\b.pdf
\media\
An.mp3
이 디렉터리를 업로드하면 Amazon S3는 다음 키 이름을 사용해요.
예시
a.txt
b.pdf
media/An.mp3
예시
다음 C# 예시는 디렉터리를 Amazon S3 버킷에 업로드해요. 다양한 TransferUtility.UploadDirectory 오버로드를 사용해 디렉터리를 업로드하는 방법을 보여줘요. 업로드를 호출할 때마다 이전 업로드를 대체해요. 코드 예시를 설정하고 실행하는 방법에 대한 자세한 내용은 AWS SDK for .NET 개발자 가이드의 AWS SDK for .NET 시작하기를 참고하세요.
using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
using System;
using System.IO;
using System.Threading.Tasks;
namespace Amazon.DocSamples.S3
{
class UploadDirMPUHighLevelAPITest
{
private const string existingBucketName = "*** bucket name ***";
private const string directoryPath = @"*** directory path ***";
// The example uploads only .txt files.
private const string wildCard = "*.txt";
// Specify your bucket region (an example region is shown).
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
private static IAmazonS3 s3Client;
static void Main()
{
s3Client = new AmazonS3Client(bucketRegion);
UploadDirAsync().Wait();
}
private static async Task UploadDirAsync()
{
try
{
var directoryTransferUtility =
new TransferUtility(s3Client);
// 1. Upload a directory.
await directoryTransferUtility.UploadDirectoryAsync(directoryPath,
existingBucketName);
Console.WriteLine("Upload statement 1 completed");
// 2. Upload only the .txt files from a directory
// and search recursively.
await directoryTransferUtility.UploadDirectoryAsync(
directoryPath,
existingBucketName,
wildCard,
SearchOption.AllDirectories);
Console.WriteLine("Upload statement 2 completed");
// 3. The same as Step 2 and some optional configuration.
// Search recursively for .txt files to upload.
var request = new TransferUtilityUploadDirectoryRequest
{
BucketName = existingBucketName,
Directory = directoryPath,
SearchOption = SearchOption.AllDirectories,
SearchPattern = wildCard
};
await directoryTransferUtility.UploadDirectoryAsync(request);
Console.WriteLine("Upload statement 3 completed");
}
catch (AmazonS3Exception e)
{
Console.WriteLine(
"Error encountered ***. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine(
"Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
}
}
}