forked from Gutenberg-Technology/cg-file-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcg-file-upload-worker.js
49 lines (47 loc) · 1.28 KB
/
cg-file-upload-worker.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
var uploadChunk;
uploadChunk = function(blob, url, method, filename, chunk, chunks) {
var formData, xhr;
xhr = new XMLHttpRequest;
xhr.open(method, url, false);
xhr.onerror = function() {
throw new Error('error while uploading');
};
formData = new FormData;
formData.append('name', filename);
formData.append('chunk', chunk);
formData.append('chunks', chunks);
formData.append('file', blob);
xhr.send(formData);
return xhr.responseText;
};
this.onmessage = function(e) {
var blob, blobs, bytes_per_chunk, data, end, file, i, j, len, method, name, response, size, start, url;
file = e.data.file;
url = e.data.url;
method = e.data.method || 'POST';
name = e.data.name;
blobs = [];
bytes_per_chunk = 1024 * 1024 * 10;
start = 0;
end = bytes_per_chunk;
size = file.size;
while (start < size) {
blobs.push(file.slice(start, end));
start = end;
end = start + bytes_per_chunk;
}
for (i = j = 0, len = blobs.length; j < len; i = ++j) {
blob = blobs[i];
response = uploadChunk(blob, url, method, name, i, blobs.length);
data = {
message: 'progress',
body: ((i + 1) * 100 / blobs.length).toFixed(0)
};
this.postMessage(data);
}
data = {
message: 'load',
body: response
};
return this.postMessage(data);
};