aboutsummaryrefslogtreecommitdiffstats
path: root/app/javascript/activestorage/blob_upload.js
diff options
context:
space:
mode:
Diffstat (limited to 'app/javascript/activestorage/blob_upload.js')
-rw-r--r--app/javascript/activestorage/blob_upload.js31
1 files changed, 31 insertions, 0 deletions
diff --git a/app/javascript/activestorage/blob_upload.js b/app/javascript/activestorage/blob_upload.js
new file mode 100644
index 0000000000..8c1335c56c
--- /dev/null
+++ b/app/javascript/activestorage/blob_upload.js
@@ -0,0 +1,31 @@
+export class BlobUpload {
+ constructor(blob) {
+ this.blob = blob
+ this.file = blob.file
+
+ this.xhr = new XMLHttpRequest
+ this.xhr.open("PUT", blob.uploadURL, true)
+ this.xhr.setRequestHeader("Content-Type", blob.attributes.content_type)
+ this.xhr.setRequestHeader("Content-MD5", blob.attributes.checksum)
+ 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, this.xhr.response)
+ } else {
+ this.requestDidError(event)
+ }
+ }
+
+ requestDidError(event) {
+ this.callback(`Error storing "${this.file.name}". Status: ${this.xhr.status}`)
+ }
+}