1.
:
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.