Skip to content

Instantly share code, notes, and snippets.

@sostenesapollo
Created May 6, 2024 12:10
Show Gist options
  • Save sostenesapollo/f587a5d41d900edf81bbb59e4b82b62b to your computer and use it in GitHub Desktop.
Save sostenesapollo/f587a5d41d900edf81bbb59e4b82b62b to your computer and use it in GitHub Desktop.
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { readFileSync } from "fs";
import { uuid } from "uuidv4";
const STORAGE_BUCKET = 'voluntario'
const client = new S3Client({
region: "us-east-2",
credentials: {
accessKeyId: "",
secretAccessKey: "",
},
});
export const formatFilenameWithBucket = (filename) => typeof filename === 'string' ?
filename?.includes('http') ? filename : `https://${STORAGE_BUCKET}.s3.amazonaws.com/${filename}` : null
const uploadStreamToS3 = async (b64, filename, type) => {
const buf = Buffer.from(
b64.replace(/^data:image\/\w+;base64,/, ""),
"base64"
);
const filetUUID = uuid();
const getExtension = filename?.slice(
((filename.lastIndexOf(".") - 1) >>> 0) + 2
);
const fName = filetUUID + "." + getExtension;
console.log({fName});
const params = {
Bucket: STORAGE_BUCKET,
Key: fName,
Body: buf,
ACL: "public-read",
ContentType: type,
};
await client.send(new PutObjectCommand(params));
return fName;
};
const base64 = readFileSync('public/pedegas.png', 'base64')
const filename = `${uuid()}.png`
console.log({filename, base64: base64.length});
uploadStreamToS3(base64, filename, 'image/png').then((imageUrl)=>{
console.log('result', {imageUrl, fileUrl: formatFilenameWithBucket(imageUrl)});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment