diff options
Diffstat (limited to 'activestorage/app/javascript/activestorage/blob_upload.js')
-rw-r--r-- | activestorage/app/javascript/activestorage/blob_upload.js | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/activestorage/app/javascript/activestorage/blob_upload.js b/activestorage/app/javascript/activestorage/blob_upload.js new file mode 100644 index 0000000000..99bf0c9e30 --- /dev/null +++ b/activestorage/app/javascript/activestorage/blob_upload.js @@ -0,0 +1,34 @@ +export class BlobUpload { + constructor(blob) { + this.blob = blob + this.file = blob.file + + const { url, headers } = blob.directUploadData + + this.xhr = new XMLHttpRequest + this.xhr.open("PUT", url, true) + for (const key in headers) { + this.xhr.setRequestHeader(key, headers[key]) + } + this.xhr.addEventListener("load", event => this.requestDidLoad(event)) + this.xhr.addEventListener("error", event => this.requestDidError(event)) + } + + create(callback) { + this.callback = callback + this.xhr.send(this.file) + } + + requestDidLoad(event) { + const { status, response } = this.xhr + if (status >= 200 && status < 300) { + this.callback(null, response) + } else { + this.requestDidError(event) + } + } + + requestDidError(event) { + this.callback(`Error storing "${this.file.name}". Status: ${this.xhr.status}`) + } +} |