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
|
import { as_type } from './crud.types'
export function crud_upload(type, id, fd, dispatch) => {
return new Promise( (resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", '/' + type + '/' + id + '/upload/')
xhr.send(fd)
dispatch && dispatch({ type: as_type(type, 'upload_loading')})
function uploadProgress (e) {
if (e.lengthComputable) {
dispatch && dispatch({
type: as_type(type, 'upload_progress'),
percent: Math.round(e.loaded * 100 / e.total),
[type]: id,
})
}
else {
dispatch && dispatch({
type: as_type(type, 'upload_error'),
error: 'unable to compute upload progress',
[type]: id,
})
}
}
function uploadComplete (e) {
try {
const data = JSON.parse(e.target.responseText)
} catch (e) {
dispatch && dispatch({
type: as_type(type, 'upload_error'),
error: 'upload failed',
[type]: id,
})
return
}
dispatch && dispatch({
type: as_type(type, 'upload_complete'),
data
[type]: id,
})
}
uploadFailed = function (evt) {
dispatch && dispatch({
type: as_type(type, 'upload_error'),
error: 'upload failed',
[type]: id,
})
}
uploadCancelled = function (evt) {
dispatch && dispatch({
type: as_type(type, 'upload_error'),
error: 'upload cancelled'
[type]: id,
})
}
})
}
export function uploadAction(type, id, fd) {
return dispatch => crud_upload(type, id, fd, dispatch)
}
|