Skip to content

Instantly share code, notes, and snippets.

@beatlecz
Created March 6, 2015 09:36
Show Gist options
  • Save beatlecz/6ecd3f288561f4c59146 to your computer and use it in GitHub Desktop.
Save beatlecz/6ecd3f288561f4c59146 to your computer and use it in GitHub Desktop.
class CORS
self = this
constructor: ->
createCORSRequest = (method, url) ->
xhr = new XMLHttpRequest()
if(xhr.withCredentials != 'undefined')
xhr.open method, url, true
else if typeof(XDomainRequest) != 'undefined'
xhr = new XDomainRequest()
xhr.open method, url
else
xhr = null
xhr
executeOnSignedUrl = (file, callback) ->
xhr = new XMLHttpRequest()
file.type = 'image/jpeg'
#key = file.name.replace(new RegExp(' ','g'), '_')
#xhr.open('GET', '/upload/sign?key=test/'+key+'&type='+file.type, true)
xhr.open('GET', self.opts.url, true)
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange = (e) ->
if this.readyState == 4 && this.status == 200
self.opts.remote_url = this.responseText.split('|')[1]
self.opts.key = this.responseText.split('|')[2]
self.opts.media_id = this.responseText.split('|')[3]
callback(this.responseText.split('|')[0])
#callback(decodeURIComponent(this.responseText))
else if this.readyState == 4 && this.status != 200
window.console.log('Could not contact signing script. Status = ' + this.status)
xhr.send()
this.uploadFile = (opts) ->
self.opts = opts
executeOnSignedUrl self.opts.file, (signedURL) ->
uploadToS3(self.opts.file, signedURL)
uploadToS3 = (file, url) ->
xhr = createCORSRequest('PUT', url)
if !xhr
window.console.log('CORS not supported')
else
xhr.onload = ->
if xhr.status == 200
window.console.log('Upload Completed!')
self.opts.success(self.opts.file, self.opts)
else
window.console.log('Upload error:' + xhr.status)
xhr.onerror = (error) ->
window.console.log(error)
xhr.upload.onprogress = (e) ->
if e.lengthComputable
percentLoaded = Math.round((e.loaded / e.total)*100)
self.opts.progress(percentLoaded)
#window.console.log(percentLoaded + '%')
xhr.setRequestHeader('Content-Type', file.type)
xhr.setRequestHeader('x-amz-acl', 'public-read')
xhr.send(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment