简体   繁体   中英

Using Presigned url to upload an image to Amazon S3 in C#

I am new to Amazon S3.

I've a piece of code where the file is getting uploaded to Amazon S3 in C# (.Net Framework) using Token and Secret key.

Now my requirements have changed and I've to use PreSigned url to upload the same Image/file. I'm able to generate a Presigned url but don't know how to upload the image using this PreSigned url. I tried to google but couldn't find the actual solution. Please see the below piece of code:

/// <summary>
/// Method uploads files to a folder inside the Amazon Bucket
/// </summary>
/// <param name="BucketName">Amazon Bucket</param>
/// <param name="folderName">Name of the folder to be created</param>
/// <param name="fileName">Name of the file to be uploaded inside the folder</param>
/// <param name="fileUrl">Path of the file to be uploaded inside the folder</param>
/// <returns>Returns Amazon file path as BucketName/FolderName only if the file is successfully uploaded to this folder or else returns 1 to indicate that file upload was unsuccessful</returns>
public String CreateNewFileInFolder(String BucketName, String folderName, String fileName, String fileUrl, bool StoreInParentFolder = false, string PreSignurl)
{
    try
    {

        String S3Key = new S3FileInfo(
            s3Client, 
            BucketName, 
            folderName + "/" + fileName).Exists ? Path.GetFileNameWithoutExtension(fileUrl) + "-" + Guid.NewGuid() + Path.GetExtension(fileUrl) : Path.GetFileName(fileUrl);

        PutObjectRequest request = new PutObjectRequest
        { 
            BucketName = BucketName, 
            Key = folderName + "/" + S3Key, 
            FilePath = fileUrl, 
            ContentType = GetContentType(fileName) 
        };
        s3Client.PutObject(request);
    }
    catch (Exception e)
    {

    }
}

I did the exactly same thing recently. You would need to call the PreSignedUrl with PUT request that contains the image file stream. The below is my code for that.

private static async Task UploadToS3(string filename, string preSignedUrl)
{
    await using var fileStream = File.OpenRead(filename);
    var fileStreamResponse = await new HttpClient().PutAsync(
        new Uri(preSignedUrl),
        new StreamContent(fileStream));
    fileStreamResponse.EnsureSuccessStatusCode();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM