1. Multipart uploads (for large files) with @aws-sdk/lib-storage:
For large files, use the @aws-sdk/lib-storage package, which simplifies multipart uploads. Install it first:
Bash
npm install @aws-sdk/lib-storage
Then, use Upload:
TypeScript
import { S3Client } from '@aws-sdk/client-s3';
import { Upload } from '@aws-sdk/lib-storage';
import * as fs from 'fs'; // For file system access (if uploading from a file)
async function multipartUploadToS3(bucketName: string, key: string,
filePath: string) {
const s3Client = new S3Client({}); // Configure your client here
const fileStream = fs.createReadStream(filePath);
const upload = new Upload({
client: s3Client,
params: {
Bucket: bucketName,
Key:key,
Body: fileStream,
},
});
try {
const result = await upload.done();
console.log('Multipart download successful:', result);
return `s3://${bucketName}/${key}`;
} catch (error) {
console.error('Error during multi-party download:', error);
return null;
}
}
2. Example of use:
async function yourMultipartUploadFunction() {
const bucketName = 'your-bucket-name';
const key = 'large-file.zip'; const filePath = '/path/to/your/large-file.zip';
const s3Url = await multipartUploadToS3(bucketName, key, filePath);
if (s3Url) {
console.log("Multipart Upload S3 URL: ", s3Url)
} else {
console.log("Multipart Upload Failed.");
}
}
yourMultipartUploadFunction();
3. Key Improvements and Explanations:
PutObjectCommand: For simple uploads, the PutObjectCommand command is used, and the s3Client.send() method sends the command.
@aws-sdk/lib-storage: For multipart uploads, the Upload class from @awssdk/lib-storage handles the complexity of splitting and uploading large files. Error Handling: The code includes try...catch blocks to handle potential errors during upload.
Clear Examples: These examples demonstrate how to use PutObjectCommand and Upload.
Dependencies: This example demonstrates how to install @aws-sdk/lib-storage if you're using it.
File Streams: The multipart example demonstrates how to upload a file from the file system using a file stream.
Remember to configure your S3 client with your AWS credentials and region.
