Skip to content

Instantly share code, notes, and snippets.

@Arunmainthan
Last active December 17, 2019 11:26
Show Gist options
  • Save Arunmainthan/4f69229fb55933de7c05880bdcdb679b to your computer and use it in GitHub Desktop.
Save Arunmainthan/4f69229fb55933de7c05880bdcdb679b to your computer and use it in GitHub Desktop.
Generate S3 Presigned URL
import AWS = require('aws-sdk');
var axios = require('axios');
import { readFileSync } from 'fs'
import * as request from 'request'
import { readFile } from 'fs'
import { promisify } from 'util';
const S3_BUCKET = `your-s3-bucket`;
const getPresignedUrl = async (fileName, fileType) => {
const s3 = new AWS.S3(); // Create a new instance of S3
// Set up the payload of what we are sending to the S3 api
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 5000,
//ContentType: fileType,
// ACL: 'public-read',
ContentType: 'application/octet-stream'
};
// Make a request to the S3 API to get a signed URL which we can use to upload our file
try {
const data = await s3.getSignedUrlPromise('putObject', s3Params);
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
return returnData;
} catch (err) {
console.log('err: ', err);
}
}
(async () => {
const signature = await getPresignedUrl('car.jpg', 'image/jpeg')
console.log('signature: ', signature);
})()
import boto3
s3_client = boto3.client('s3')
response = None
try:
response = s3_client.generate_presigned_url(
'put_object',
Params={
'Bucket': 'bucket-name',
'Key': 'car.jpg'},
ExpiresIn=5000)
print(response)
except Exception as e:
print("In client error exception code")
print(e)
#cors.json
{
"CORSRules": [
{
"AllowedOrigins": ["*"],
"AllowedHeaders": ["*"],
"AllowedMethods": ["PUT", "POST", "DELETE"],
"MaxAgeSeconds": 3000
}
]
}
#create bucket with cors
aws s3api create-bucket --bucket bucket-name --acl public-read-write --region ap-southeast-2 --create-bucket-configuration LocationConstraint=ap-southeast-2
# setup cors
aws s3api put-bucket-cors --bucket bucket-name --cors-configuratio file://cors.json --region ap-southeast-2
# upload to s3 using presigned URL
curl -X PUT -v -T ./car.jpg 'https://bucket-name.s3.amazonaws.com/car.jpg?AWSAccessKeyId=AKIAIWJZU6ZOALBQK4KQ&Content-Type=application%2Foctet-stream&Expires=1576279219&Signature=K%2B0IEe5FloSxxyXwAoBXzUru2rM%3D' -H 'Content-Type: application/octet-stream'
}
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
async function putobjectUsingSignature(signatue) {
const readFilePromise = promisify(readFile);
const file = await readFilePromise('./car.jpg')
console.log('signatue.signedRequest: ', signatue.signedRequest)
request({
method: 'PUT',
url: signatue.signedRequest,
body: file,
headers: {
'Content-Type': 'application/octet-stream'
}
}, (error, response, body) => {
// console.log(response)
})
}
(async () => {
const signature = await getPresignedUrl('car.jpg', 'image/jpeg')
console.log('signature: ', signature);
await putobjectUsingSignature(signature)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment