Last active
May 12, 2024 13:48
-
-
Save prathamesh-dukare/1acf4eaf42bb3bf5c8b8a5476bf13a37 to your computer and use it in GitHub Desktop.
Nodejs snippet to get presigned url for uploading and viewwing a object in AWS S3 bucket.
This file contains hidden or 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
// Nodejs snippet to get presigned url for uploading and viewwing a object in AWS S3 bucket. | |
import { | |
GetObjectCommand, | |
PutObjectCommand, | |
S3Client, | |
} from "@aws-sdk/client-s3"; | |
import { | |
getSignedUrl, | |
S3RequestPresigner, | |
} from "@aws-sdk/s3-request-presigner"; | |
const client = new S3Client({ | |
region: "us-east-1", | |
// apiVersion: "2006-03-01", | |
// signatureVersion: "v4", | |
credentials: { | |
accessKeyId: "YOUR_ACCESS_KEY_ID", | |
secretAccessKey: "YOUR_SECRET_ACCESS_KEY", | |
}, | |
}); | |
// * Create Presigned URL for getting object | |
const createGetPresignedUrl = ({ bucket, key }) => { | |
const command = new GetObjectCommand({ Bucket: bucket, Key: key }); | |
return getSignedUrl(client, command, { expiresIn: 3600 }); | |
}; | |
// * Create Presigned URL for putting object (uploading) | |
const createPutPresignedUrl = ({ bucket, key, type }) => { | |
const command = new PutObjectCommand({ | |
Bucket: bucket, | |
Key: key, | |
ContentType: type, | |
}); | |
return getSignedUrl(client, command, { expiresIn: 3600 }); | |
}; | |
async function main() { | |
const clientUrl = await createPresignedUrlWithClient({ | |
region: "us-east-1", | |
bucket: "YOUR_BKT_NAME", | |
key: "OBJECT_PATH", | |
}); | |
const clientUrl = await createGetPresignedUrl({ | |
bucket: "YOUR_BKT_NAME", | |
key: "KEY", | |
type: "FILE_TYPE", | |
}); | |
console.log("Client URL: ", clientUrl); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment