Problem
How do you upload a PDF file 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 a unique key to identify the object in S3.
- Line 6: InputStream: Set the inputStream to the PDF stream 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 the browser can show the file as a 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
We can upload a PDF to an S3 bucket using this snippet and encrypt it using server-side encryption.