Created
April 12, 2023 14:22
-
-
Save johnpolacek/d04cb53737462990a912489da296bffd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AWS from "aws-sdk" | |
AWS.config.update({ | |
region: process.env.AWS_REGION, | |
accessKeyId: process.env.AWS_ACCESS_KEY_ID, | |
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, | |
}) | |
const s3 = new AWS.S3() | |
const BUCKET = "your-bucket-name" | |
export const transferImageToS3 = async ( | |
imageUrl: string, | |
key: string | |
): Promise<string> => { | |
try { | |
// Download the image from the URL | |
console.log("Downloading image from URL:", imageUrl) | |
const response = await fetch(imageUrl) | |
console.log("Image downloaded successfully") | |
const arrayBuffer = await response.arrayBuffer() | |
// Prepare the parameters for uploading to S3 | |
const params = { | |
Bucket: BUCKET, | |
Key: key, | |
Body: Buffer.from(arrayBuffer), | |
ContentType: | |
response.headers.get("content-type") || "application/octet-stream", | |
ContentLength: parseInt( | |
response.headers.get("content-length") || "0", | |
10 | |
), | |
} | |
console.log("Prepare for upload to S3") | |
// Upload the image to the S3 bucket | |
await s3.upload(params).promise() | |
console.log("Upload complete") | |
// Construct the public URL for the image | |
const publicUrl = `https://${BUCKET}.s3.amazonaws.com/${key}` | |
console.log("Image uploaded successfully:", publicUrl) | |
return publicUrl | |
} catch (error) { | |
console.error("Error uploading image to S3:", error) | |
throw new Error("Error uploading image to S3") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment