DEV Community

Ankur Sheel
Ankur Sheel

Posted on • Originally published at ankursheel.com on

1

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

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay