Created
April 19, 2016 14:53
-
-
Save bs1180/e9470222e07f79c7598b16edf3d5d315 to your computer and use it in GitHub Desktop.
Current method of signing S3 upload URL
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
// tools.generateId | |
function generateId(size){ | |
var text = []; | |
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
for( var i=0; i < size; i++ ) | |
text.push(possible.charAt(Math.floor(Math.random() * possible.length))); | |
return text.join(''); | |
} | |
// main signing function | |
export function getSignedRequest(file) { | |
return new Promise((resolve, reject) => { | |
getJWT() | |
.then((jwt) => { | |
request | |
.get(getURL() + "sign_s3?file_name=" + tools.generateId(64) + "&file_type="+file.type) | |
.set(headersConstructor(jwt)) | |
.end(function(err, res){ | |
if(err){ | |
console.log('ERROR ON GET SIGNED REQUEST'); | |
console.log(err); | |
reject(err); | |
} | |
resolve(res); | |
}); | |
}) | |
.catch((err) => { | |
console.log(err); | |
reject(err); | |
}); | |
}); | |
} | |
export function uploadFile(file, signed_request, url){ | |
return new Promise((resolve, reject) => { | |
let xhr = new XMLHttpRequest(); | |
xhr.open("PUT", signed_request); | |
xhr.setRequestHeader('x-amz-acl', 'public-read'); | |
xhr.onload = function() { | |
if (xhr.status === 200) { | |
resolve(url); | |
} | |
}; | |
xhr.onerror = function() { | |
console.log("Could not upload file."); | |
reject(); | |
}; | |
xhr.send(file); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment