@backstageai/common
Version:
Common code for Backstage AI services
49 lines (37 loc) • 1.34 kB
JavaScript
const { returnSecret } = require("@backstageai/common");
const AWS = require("aws-sdk");
// // Configure AWS SDK
const s3 = new AWS.S3();
async function uploadToS3(imageUrl, fileName, type = "image") {
console.log("imageUrl, fileName", imageUrl, fileName);
const BUCKET_NAME = await returnSecret("AWS_S3_BUCKET"); // Replace with your bucket name
if (!imageUrl) {
return false;
}
const extension = imageUrl.split(".").pop() || "";
// ContentType as per type (image | video)
const contentType = type === "image" ? "image/jpeg" : "video/mp4";
// Download the image to /tmp
const response = await fetch(imageUrl);
if (!response.ok) return false;
const responseBody = await response.arrayBuffer();
const buffer = Buffer.from(responseBody);
const fileKey = `${type}/${fileName}.${extension}`;
console.log("fileKey", fileKey);
const params = {
Bucket: BUCKET_NAME,
Key: fileKey, // S3 file path
Body: buffer,
ContentType: contentType,
};
try {
const uploadResult = await s3.upload(params).promise();
console.log(`Image successfully uploaded to ${uploadResult.Location}`);
// Return the uploaded image Key
return uploadResult.Key;
} catch (error) {
console.error("Error uploading image:", error);
throw error;
}
}
module.exports.uploadToS3 = uploadToS3;