aboutsummaryrefslogtreecommitdiffstats
path: root/app/javascript/activestorage/blob_upload.js
blob: 8c1335c56c133a9725e9a4aaba3c7d2e4e254c1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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}`)
  }
}