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

前端之家收集整理的这篇文章主要介绍了使用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,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.

原文链接:https://www.f2er.com/aspnet/248094.html

猜你在找的asp.Net相关文章