[英]How to create subdirectory in amazon s3 bucket
我正在使用 Amazon S3 Web 服務,但無法在我的存儲桶上創建子目錄。
我想要這樣的東西
當用戶上傳文件時,會在 S3 Bucket 上創建一個名為 user id 的子目錄,文件存儲在子目錄中。
我正在使用以下代碼
AmazonS3Client s3Client = new AmazonS3Client("AWSAccessKey", "AWSSecretKey", Amazon.RegionEndpoint.APSoutheast1);
protected void btnUpload_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(fileUpload.FileName))
{
//Saving File to local disk folder.
string filePath = Server.MapPath("aa") + "\\" + fileUpload.FileName;
string fileExtension = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf(".") + 1);
fileUpload.SaveAs(filePath);
string contentType = GetContentType(fileExtension);
//Push the given object into S3 Bucket
PutObjectRequest objReq = new PutObjectRequest
{
Key = fileUpload.FileName,
FilePath = filePath,
ContentType = contentType,
BucketName = "datastore.MyData",
CannedACL = S3CannedACL.Private,
};
PutObjectResponse response = s3Client.PutObject(objReq);
if (response.ETag != null)
{
string etag = response.ETag;
string versionID = response.VersionId;
Response.Write("<script>alert('File uploaded to S3 Bucket Successfully.');</script>");
}
//Deleting Localy Saved File
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
private string GetContentType(string fileExtension)
{
string contentType = string.Empty;
switch (fileExtension)
{
case "bmp": contentType = "image/bmp"; break;
case "jpeg": contentType = "image/jpeg"; break;
case "jpg": contentType = "image/jpg"; break;
case "gif": contentType = "image/gif"; break;
case "tiff": contentType = "image/tiff"; break;
case "png": contentType = "image/png"; break;
case "plain": contentType = "text/plain"; break;
case "rtf": contentType = "text/rtf"; break;
case "msword": contentType = "application/msword"; break;
case "zip": contentType = "application/zip"; break;
case "mpeg": contentType = "audio/mpeg"; break;
case "pdf": contentType = "application/pdf"; break;
case "xgzip": contentType = "application/x-gzip"; break;
case "xcompressed": contentType = "applicatoin/x-compressed"; break;
}
return contentType;
}
請幫助我實現這一目標。
s3
中沒有文件夾,只有key/value
對。 鍵可以包含斜杠("/")
,這將使它在管理控制台中顯示為文件夾,但從編程上講,它不是一個文件夾,而是一個字符串值。
我們使用末尾帶有字符“/”的 FileKey 來表示您要創建文件夾。
PutObjectRequest objReq = new PutObjectRequest
{
Key = "Name of the folder you want to create/" fileUpload.FileName,
FilePath = filePath,
ContentType = contentType,
BucketName = "datastore.MyData",
CannedACL = S3CannedACL.Private,
};
你也可以使用這個方法。
string S3FileDir = "/Demo/Test/";
TransferUtility fileTransferUtility = new TransferUtility(keyId,secretekey,RegionEndpoint.USWest);
fileTransferUtility.Upload(localFilePath, BucketName + S3FileDir);
最簡單的方法是使用 TransferUtility。
var fileTransferUtility = new TransferUtility(_s3Client);
fileTransferUtility.Upload(localFilePath, bucketName+"/"+ subFolder);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.