使用ASP.NET SDK将文件上载到S3存储桶的文件夹

如何使用AWS SDK for ASP.NET将文件上载到特定文件夹? – 我能够通过指定存储桶名称(request.WithBucketName)来上传文件,但我希望能够将文件上传到存储桶本身的特定文件夹.

这是我用来将文件上传到单个存储桶的代码:

public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType, string toWhichBucketName)
{

    try
    {
        client = Amazon.AWSClientFactory.CreateAmazonS3Client(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY);
        PutObjectRequest request = new PutObjectRequest();
        request.WithKey(uploadAsFileName);
        request.WithInputStream(ImageStream);
        request.WithBucketName(toWhichBucketName);
        request.CannedACL = filePermission;
        request.StorageClass = storageType;

        client.PutObject(request);
        client.Dispose();
    }
    catch
    {            
        return false;
    }
    return true;

}

希望这段代码能帮到你.

要将文件添加到存储桶中的文件夹,您需要更新PutObjectRequest的Key以在文件名前包含该文件夹.

public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType, string toWhichBucketName)
{
    try
    {
        using(client = Amazon.AWSClientFactory.CreateAmazonS3Client(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY))
        {
           PutObjectRequest request = new PutObjectRequest();
           request.WithKey( "folder" + "/" + uploadAsFileName );
           request.WithInputStream(ImageStream);
           request.WithBucketName(toWhichBucketName);
           request.CannedACL = filePermission;
           request.StorageClass = storageType;

           client.PutObject(request);
        }
    }
    catch
    {            
        return false;
    }
    return true;
}

This post讨论将文件上传到文件夹.他们正在使用TransferUtilityUploadRequest,但它应该与PutObjectRequest一起使用.滚动到相关示例的底部.

This post显示了如何在不向其上传文件的情况下创建文件夹.

希望这有用

编辑:更新了代码以使用using块而不是按照最佳实践调用Dispose.

相关文章
相关标签/搜索