.net 上传amazon s3后获取文件url

jhiyze9q  于 2023-01-18  发布在  .NET
关注(0)|答案(2)|浏览(172)

上传文件到amazons3服务器后,我需要得到文件的url。这是我的上传代码。如何返回amazons3路径?

public static bool UploadToS3(string bucketName, string bucketFilePath, Byte[] localPath)
{
    var client = Amazon.AWSClientFactory.CreateAmazonS3Client(Config.EmailServer.AwsAccessKey, Config.EmailServer.AwsSecretKey, Amazon.RegionEndpoint.EUWest1);

    PutObjectRequest request = new PutObjectRequest()
    {
        BucketName = bucketName,
        Key = bucketFilePath,
        InputStream = new MemoryStream(localPath),
        AutoCloseStream = true,
        CannedACL = S3CannedACL.PublicRead,
        StorageClass = S3StorageClass.ReducedRedundancy                
    };
    
    PutObjectResponse response = client.PutObject(request);
    return true;
}
44u64gxh

44u64gxh1#

简单地说,您可以生成下载到期链接后,上传完成.
示例:

var expiryUrlRequest = new GetPreSignedUrlRequest()
                           .WithBucketName(BucketName)
                           .WithKey(Key)
                           .WithExpires(DateTime.Now.AddDays(10));

string url = _amazonS3Client.GetPreSignedURL(expiryUrlRequest);
wlwcrazw

wlwcrazw2#

试试这个方法

GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();
request.BucketName = "my-bucket-name";
request.Key        = "secret_plans.txt";
request.Expires    = DateTime.Now.AddHours(1);
request.Protocol   = Protocol.HTTP;
string url = client.GetPreSignedURL(request);
Console.WriteLine(url);

相关问题