loading...

How do you upload a PDF received from an API to AWS S3?

ankursheel profile image Ankur Sheel Originally published at ankursheel.com on ・1 min read

Problem

How do you upload a PDF file that was generated by a 3rd party API to an AWS S3 bucket and protect it using server-side encryption?

Solution

Let’s assume that we have got the pdf as a stream from calling our API endpoint.

Stream pdfStream = api.GetPdfAsStream();

Snippet

Let’s see the code before talking about what is happening.

var s3Client = new AmazonS3Client(RegionEndpoint.USEast1);
var s3Request = new PutObjectRequest
{
    BucketName = "Bucket Name",
    Key = Guid.NewGuid().ToString(),
    InputStream = pdfStream,
    ServerSideEncryptionMethod = ServerSideEncryptionMethod.AWSKMS,
    ContentType = "application/pdf",
    Headers = { ContentDisposition = $"attachment; \"filename=\"File Name\"" },
};

var s3Response = await s3Client.PutObjectAsync(s3Request);
  • Line 1 : Setup the S3 client with the region we want to connect to
  • Line 2 : Create a new PutObjectRequest because we want to upload a file to S3.
  • Line 4 : BucketName : Set the bucket name to which the PDF needs to be uploaded.
  • Line 5 : Key : Create an unique key to identify the object in S3.
  • Line 6 : InputStream : Set the the inputStream to the PDF stream that we received from the API.
  • Line 7 : ServerSideEncryptionMethod : Use the AWS Key Management Service to encrypt the PDF.
  • Line 8 : ContentType : Set the content type to application/pdf so that the browser can show the file asa PDF.
  • Line 9 : Headers : Add some common headers
    • ContentDisposition to attachment to indicate that the file should be downloaded.
    • filename to the name of the File.
  • Line 12 : Start the asynchronous execution of the PutObject operation.

Conclusion

Using this snippet, we are able to upload a PDF to a S3 bucket and encrypt it using server-side encryption.

Discussion

markdown guide