Code
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; const uploadFileToS3 = async (bucketName: string, key: string, fileContent: string) => { // Create S3 client const s3Client = new S3Client({}); // Set upload parameters const params = { Body: fileContent, Bucket: bucketName, Key: key, }; try { // Upload file to S3 const command = new PutObjectCommand(params); const response = await s3Client.send(command); console.log("File uploaded successfully", response); } catch (error) { console.error("Error uploading file", error); } }; const bucketName = "my-bucket"; const key = "my-file.txt"; const fileContent = "This is the content of my file"; uploadFileToS3(bucketName, key, fileContent);
Detailed Code Explanation
In this code, we use the AWS SDK for JavaScript to upload a file to Amazon S3 (Simple Storage Service). The code is written in TypeScript and uses the S3Client and PutObjectCommand classes from the @aws-sdk/client-s3
package.
-
We import the required classes from the
@aws-sdk/client-s3
package: S3Client and PutObjectCommand. -
The
uploadFileToS3
function takes three parameters:bucketName
: The name of the S3 bucket where the file will be uploaded.key
: The key (filename) of the file in the S3 bucket.fileContent
: The content of the file to be uploaded.
-
Inside the
uploadFileToS3
function, we create an instance of the S3Client class. -
We define the upload parameters (Body, Bucket, and Key) for the PutObjectCommand. The
Body
parameter contains the content of the file to be uploaded,Bucket
specifies the name of the S3 bucket, andKey
specifies the key (filename) of the file in the S3 bucket. -
We try to execute the PutObjectCommand using the
await
keyword, which sends the command to the S3 service and returns a response. -
If the file is uploaded successfully, we log a success message along with the response object to the console.
-
If an error occurs during the upload, we log an error message along with the error object to the console.
-
Finally, we call the
uploadFileToS3
function with the required parameters:bucketName
,key
, andfileContent
.
Expected Output Format
The expected output format is a JSON object representing the response returned by the S3 service after successfully uploading the file. In case of success, the output will contain information such as the ETag (Entity Tag) of the uploaded object and other metadata. If an error occurs, the output will contain error details.
Considerations & Caveats
- Make sure you have valid AWS credentials configured on your local environment or deployment platform. Without valid credentials, the code will fail to authenticate and upload the file to S3.
- Take care of the file size limitations. By default, the maximum file size that can be uploaded to Amazon S3 is 5 TB. If your file exceeds this limit, you may need to split it into smaller parts or consider using the Amazon Multipart Upload API.
- Ensure that the bucket you want to upload the file to exists and you have the necessary permissions to perform the upload operation.
Required IAM Permissions and Example Policy
To upload a file to an S3 bucket, the AWS Identity and Access Management (IAM) user or role executing the code must have the necessary permissions. Below is an example IAM policy that grants the minimum required permissions for the file upload operation:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::my-bucket/*" } ] }
In the Resource
field of the policy, replace my-bucket
with the name of your S3 bucket.
FAQ
Q: Can I upload multiple files using the same code?
A: Yes, you can upload multiple files using the same code by calling the uploadFileToS3
function multiple times with different file parameters.
Q: How can I handle file uploads with progress tracking?
A: The current code does not provide progress tracking out of the box. However, you can leverage the Multipart Upload API provided by the AWS SDK for JavaScript to handle file uploads with progress tracking.
Q: Is there a limit on the number of files I can upload to an S3 bucket?
A: There is no hard limit on the number of files you can upload to an S3 bucket. However, there may be practical limits based on the size and performance of your bucket, as well as any applicable AWS service limits.
Q: Can I specify additional metadata for my uploaded file?
A: Yes, you can specify additional metadata for your uploaded file by including additional parameters in the params
object passed to the PutObjectCommand. For example, you can set custom metadata headers using the Metadata
property.