diff options
author | Javan Makhmali <javan@javan.us> | 2017-07-27 19:47:03 -0400 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2017-07-27 18:47:03 -0500 |
commit | 6262891b5669716db7c46dcdcec685d2f55903b5 (patch) | |
tree | 51528471efe698fe0e66d0f0359a5d5eaefab995 /app/javascript/activestorage/blob_record.js | |
parent | dc235c4d1366b4f3185d30a8a4e35ad12173fd89 (diff) | |
download | rails-6262891b5669716db7c46dcdcec685d2f55903b5.tar.gz rails-6262891b5669716db7c46dcdcec685d2f55903b5.tar.bz2 rails-6262891b5669716db7c46dcdcec685d2f55903b5.zip |
Add JavaScript direct upload support (#81)
Diffstat (limited to 'app/javascript/activestorage/blob_record.js')
-rw-r--r-- | app/javascript/activestorage/blob_record.js | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/app/javascript/activestorage/blob_record.js b/app/javascript/activestorage/blob_record.js new file mode 100644 index 0000000000..9b7801afd5 --- /dev/null +++ b/app/javascript/activestorage/blob_record.js @@ -0,0 +1,52 @@ +import { getMetaValue } from "./helpers" + +export class BlobRecord { + constructor(file, checksum, url) { + this.file = file + + this.attributes = { + filename: file.name, + content_type: file.type, + byte_size: file.size, + checksum: checksum + } + + this.xhr = new XMLHttpRequest + this.xhr.open("POST", url, true) + this.xhr.responseType = "json" + this.xhr.setRequestHeader("Content-Type", "application/json") + this.xhr.setRequestHeader("Accept", "application/json") + this.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") + this.xhr.setRequestHeader("X-CSRF-Token", getMetaValue("csrf-token")) + this.xhr.addEventListener("load", event => this.requestDidLoad(event)) + this.xhr.addEventListener("error", event => this.requestDidError(event)) + } + + create(callback) { + this.callback = callback + this.xhr.send(JSON.stringify({ blob: this.attributes })) + } + + requestDidLoad(event) { + const { status, response } = this.xhr + if (status >= 200 && status < 300) { + this.attributes.signed_id = response.signed_blob_id + this.uploadURL = response.upload_to_url + this.callback(null, this.toJSON()) + } else { + this.requestDidError(event) + } + } + + requestDidError(event) { + this.callback(`Error creating Blob for "${this.file.name}". Status: ${this.xhr.status}`) + } + + toJSON() { + const result = {} + for (const key in this.attributes) { + result[key] = this.attributes[key] + } + return result + } +} |