/
blob_record.js
75 lines (64 loc) · 2.04 KB
/
blob_record.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { getMetaValue } from "./helpers"
export class BlobRecord {
constructor(file, checksum, url, directUploadToken, attachmentName) {
this.file = file
this.attributes = {
filename: file.name,
content_type: file.type || "application/octet-stream",
byte_size: file.size,
checksum: checksum,
direct_upload_token: directUploadToken,
attachment_name: attachmentName
}
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")
const csrfToken = getMetaValue("csrf-token")
if (csrfToken != undefined) {
this.xhr.setRequestHeader("X-CSRF-Token", csrfToken)
}
this.xhr.addEventListener("load", event => this.requestDidLoad(event))
this.xhr.addEventListener("error", event => this.requestDidError(event))
}
get status() {
return this.xhr.status
}
get response() {
const { responseType, response } = this.xhr
if (responseType == "json") {
return response
} else {
// Shim for IE 11: https://connect.microsoft.com/IE/feedback/details/794808
return JSON.parse(response)
}
}
create(callback) {
this.callback = callback
this.xhr.send(JSON.stringify({ blob: this.attributes }))
}
requestDidLoad(event) {
if (this.status >= 200 && this.status < 300) {
const { response } = this
const { direct_upload } = response
delete response.direct_upload
this.attributes = response
this.directUploadData = direct_upload
this.callback(null, this.toJSON())
} else {
this.requestDidError(event)
}
}
requestDidError(event) {
this.callback(`Error creating Blob for "${this.file.name}". Status: ${this.status}`)
}
toJSON() {
const result = {}
for (const key in this.attributes) {
result[key] = this.attributes[key]
}
return result
}
}