Skip to content

Instantly share code, notes, and snippets.

@heymichaelp
Last active December 11, 2015 07:19
Show Gist options
  • Save heymichaelp/4565831 to your computer and use it in GitHub Desktop.
Save heymichaelp/4565831 to your computer and use it in GitHub Desktop.
createCORSRequest = (method, url) ->
xhr = new XMLHttpRequest()
if "withCredentials" of xhr
xhr.open method, url, true
else unless typeof XDomainRequest is "undefined"
xhr = new XDomainRequest()
xhr.open method, url
else
xhr = null
xhr
handleFileSelect = (evt) ->
setProgress 0, "Upload started."
files = evt.target.files
output = []
i = 0
f = undefined
while f = files[i]
uploadFile f
i++
###
Execute the given callback with the signed response.
###
executeOnSignedUrl = (file, callback) ->
xhr = new XMLHttpRequest()
xhr.open "GET", "signput.php?name=" + file.name + "&type=" + file.type, true
# Hack to pass bytes through unprocessed.
xhr.overrideMimeType "text/plain; charset=x-user-defined"
xhr.onreadystatechange = (e) ->
if @readyState is 4 and @status is 200
callback decodeURIComponent(@responseText)
else setProgress 0, "Could not contact signing script. Status = " + @status if @readyState is 4 and @status isnt 200
xhr.send()
uploadFile = (file) ->
executeOnSignedUrl file, (signedURL) ->
uploadToS3 file, signedURL
###
Use a CORS call to upload the given file to S3. Assumes the url
parameter has been signed and is accessible for upload.
###
uploadToS3 = (file, url) ->
xhr = createCORSRequest("PUT", url)
unless xhr
setProgress 0, "CORS not supported"
else
xhr.onload = ->
if xhr.status is 200
setProgress 100, "Upload completed."
else
setProgress 0, "Upload error: " + xhr.status
xhr.onerror = ->
setProgress 0, "XHR error."
xhr.upload.onprogress = (e) ->
if e.lengthComputable
percentLoaded = Math.round((e.loaded / e.total) * 100)
setProgress percentLoaded, (if percentLoaded is 100 then "Finalizing." else "Uploading.")
xhr.setRequestHeader "Content-Type", file.type
xhr.setRequestHeader "x-amz-acl", "public-read"
xhr.send file
setProgress = (percent, statusLabel) ->
progress = document.querySelector(".percent")
progress.style.width = percent + "%"
progress.textContent = percent + "%"
document.getElementById("progress_bar").className = "loading"
document.getElementById("status").innerText = statusLabel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment