Here's how to properly use the Amazon S3 v3 API

Here's how to properly use the Amazon S3 v3 API

By medeb | personalblog | 13 May 2025


1. 491265b539954d95a3e3b53343437996f9f5e4b39e0600a8820ede976fca98f1.png:
Import the necessary modules:
TypeScript
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
Create an S3Client instance:
TypeScript
const client = new S3Client({
region: 'your-region', // Replace with your AWS region
credentials: {
accessKeyId: 'your-access-key-id', // Replace with your access key ID
secretAccessKey: 'your-secret-access-key', // Replace with your access key
secret
},
}); Create a PutObjectCommand command:
TypeScript
const command = new PutObjectCommand({
Bucket: 'your-bucket-name', // Replace with your bucket name
Key: 'your-object-key', // Replace with the desired object key
(filename)
Body: 'your-file-data', // Replace with the file data (e.g., a buffer, string, or stream)
ContentType: 'your-content-type', // Optional. Example: 'image/jpeg'
});
Send the command to Amazon S3
TypeScript
client.send(command)
.then((response) => {
console.log('File uploaded successfully:', response);
})
.catch((error) => {
console.error('Error uploading file:', error);
});
2. Example with HTML file
TypeScript
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
// ... other code ...
async uploadFile(file: File, bucketName: string, objectKey: string,
contentType: string) {
const client = new S3Client({
region: 'your-region',
credentials: {
accessKeyId: 'your-access-key-id',
secretAccessKey: 'your-secret-access-key',
},
});
const command = new PutObjectCommand({
Bucket: bucketName,
Key: objectKey,
Body: file,
ContentType: contentType,
});
try {
const response = await client.send(command);
console.log('File uploaded successfully:', response);
return response; } catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
//Example of use in an Angular component.
//In your HTML code, you must have an input of type file.
//
onFileSelected(event: any) {
const file = event.target.files[0];
if(file){
this.uploadFile(file, 'your-bucket-name', file.name,
file.type).then(()=>{
// handle success.
}).catch(()=>{
// handle error.
});
}
}
3. Key Points
The AWS SDK v3 is modular, allowing you to import specific commands like
PutObjectCommand.
The Body property of PutObjectCommand accepts various data types,
including Buffer, String, and Stream.
Always handle errors with try...catch or .catch().

Never hard-code your credentials into client-side code.

How do you rate this article?

2



personalblog
personalblog

My daily experience in crypto world

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.