How to Upload File to S3 in AWS: Simple Guide
To upload a file to AWS S3, use the
putObject method from the AWS SDK, specifying the Bucket, Key (file name), and Body (file content). This sends your file to the chosen S3 bucket securely and efficiently.Syntax
The main method to upload a file to S3 is putObject. You need to provide:
- Bucket: The name of your S3 bucket.
- Key: The file name or path inside the bucket.
- Body: The actual file content or data to upload.
This method uploads the file to the specified location in your S3 storage.
javascript
s3.putObject({
Bucket: 'your-bucket-name',
Key: 'file-name.ext',
Body: fileContent
}, callback);Example
This example shows how to upload a local file to S3 using Node.js AWS SDK v3. It reads the file and uploads it to your bucket.
javascript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; import { readFileSync } from "fs"; const REGION = "us-east-1"; // change to your region const s3Client = new S3Client({ region: REGION }); async function uploadFile() { try { const fileContent = readFileSync("./example.txt"); const uploadParams = { Bucket: "your-bucket-name", Key: "example.txt", Body: fileContent }; const command = new PutObjectCommand(uploadParams); const response = await s3Client.send(command); console.log("Upload successful", response); } catch (err) { console.error("Error uploading file:", err); } } uploadFile();
Output
Upload successful {}
Common Pitfalls
Common mistakes when uploading files to S3 include:
- Using incorrect bucket names or missing permissions causing access errors.
- Not reading the file content properly before upload.
- Forgetting to set the correct region in the client configuration.
- Not handling errors from the upload call.
Always check your AWS credentials and bucket policies to ensure upload is allowed.
javascript
/* Wrong: Missing file content or wrong parameter names */ s3.putObject({ Bucket: 'my-bucket', Key: 'file.txt', // Body is missing }, (err, data) => { if (err) console.log('Upload failed', err); }); /* Right: Include Body with file data */ s3.putObject({ Bucket: 'my-bucket', Key: 'file.txt', Body: fileContent }, (err, data) => { if (err) console.log('Upload failed', err); else console.log('Upload succeeded'); });
Quick Reference
Remember these tips for smooth file uploads to S3:
- Set correct Bucket and Key.
- Provide file data in Body.
- Configure AWS region and credentials properly.
- Handle errors to catch upload issues.
- Use AWS SDK v3 for modern, supported methods.
Key Takeaways
Use AWS SDK's putObject method with Bucket, Key, and Body to upload files to S3.
Always provide the file content correctly and configure your AWS region and credentials.
Check bucket permissions and handle errors to avoid upload failures.
Use the latest AWS SDK version for best support and features.