仰望星辰工作室

gitcat

gitcat/ webroot/static/release-upload.js 4.7 KB · 148 行 原始文件
1/* 发行版附件分片上传:8MB/片,顺序发送,单片失败自动重试,
2 全程 fetch + Blob 切片,内存占用只有单片大小。 */
3(function () {
4 'use strict';
5
6 var box = document.getElementById('release-upload');
7 if (!box) return;
8
9 var base = box.getAttribute('data-base') || '';
10 var csrfEl = document.getElementById('upload-csrf');
11 var input = document.getElementById('release-file');
12 var btn = document.getElementById('release-upload-btn');
13 var list = document.getElementById('upload-list');
14 var csrf = csrfEl ? csrfEl.value : '';
15
16 function el(tag, cls, text) {
17 var n = document.createElement(tag);
18 if (cls) n.className = cls;
19 if (text !== undefined) n.textContent = text;
20 return n;
21 }
22
23 function csrfQuery() {
24 return 'csrf=' + encodeURIComponent(csrf);
25 }
26
27 function readJSON(res) {
28 return res.json().then(function (j) {
29 if (!res.ok) {
30 throw new Error(j.error || ('HTTP ' + res.status));
31 }
32 return j;
33 }, function () {
34 throw new Error('HTTP ' + res.status);
35 });
36 }
37
38 /* 带重试的 fetch:网络抖动 / 瞬时 5xx 时最多再试两次。 */
39 function fetchRetry(build, attempts) {
40 function once(n) {
41 return build().catch(function (err) {
42 if (n + 1 >= attempts) throw err;
43 return new Promise(function (resolve) {
44 setTimeout(resolve, 1500);
45 }).then(function () { return once(n + 1); });
46 });
47 }
48 return once(0);
49 }
50
51 function uploadFile(file, row, bar, status) {
52 var initURL = base + '/upload/init?' + csrfQuery();
53 return fetch(initURL, {
54 method: 'POST',
55 headers: { 'Content-Type': 'application/json' },
56 body: JSON.stringify({ name: file.name, size: file.size })
57 }).then(readJSON).then(function (info) {
58 var chunkSize = info.chunk_size || 8 * 1024 * 1024;
59 var total = Math.max(1, Math.ceil(file.size / chunkSize));
60 var i = 0;
61
62 function next() {
63 if (i >= total) return null;
64 var start = i * chunkSize;
65 var blob = file.slice(start, Math.min(start + chunkSize, file.size));
66 var idx = i;
67 return fetchRetry(function () {
68 return fetch(base + '/upload/' + info.upload_id + '?index=' + idx + '&' + csrfQuery(), {
69 method: 'PUT',
70 body: blob
71 }).then(readJSON);
72 }, 3).then(function () {
73 i++;
74 var pct = Math.round(i / total * 100);
75 bar.value = pct;
76 status.textContent = pct + '%';
77 return next();
78 });
79 }
80
81 return next().then(function () {
82 status.textContent = '合并中…';
83 return fetchRetry(function () {
84 return fetch(base + '/upload/' + info.upload_id + '/complete?' + csrfQuery(), {
85 method: 'POST'
86 }).then(readJSON);
87 }, 3);
88 });
89 });
90 }
91
92 function uploadQueue(files) {
93 var chain = Promise.resolve();
94 files.forEach(function (file) {
95 var row = el('li', 'upload-item');
96 var name = el('span', 'upload-name', file.name + '(' + humanSize(file.size) + ')');
97 var bar = document.createElement('progress');
98 bar.max = 100;
99 bar.value = 0;
100 var status = el('span', 'upload-status', '排队中…');
101 row.appendChild(name);
102 row.appendChild(bar);
103 row.appendChild(status);
104 list.appendChild(row);
105
106 chain = chain.then(function () {
107 status.textContent = '0%';
108 return uploadFile(file, row, bar, status);
109 }).then(function () {
110 row.classList.add('done');
111 bar.value = 100;
112 status.textContent = '完成';
113 }).catch(function (err) {
114 row.classList.add('failed');
115 status.textContent = '失败:' + (err && err.message ? err.message : '未知错误');
116 });
117 });
118 return chain.then(function () {
119 uploading = false;
120 input.disabled = false;
121 btn.disabled = false;
122 // 有完成的项才刷新页面,让附件列表与校验值出现。
123 if (list.querySelector('.upload-item.done')) {
124 setTimeout(function () { location.reload(); }, 800);
125 }
126 });
127 }
128
129 function humanSize(n) {
130 var units = ['B', 'KB', 'MB', 'GB', 'TB'];
131 var f = n, i = 0;
132 while (f >= 1024 && i < units.length - 1) { f /= 1024; i++; }
133 return (i === 0 ? f : f.toFixed(1)) + ' ' + units[i];
134 }
135
136 var uploading = false;
137 btn.addEventListener('click', function () {
138 if (uploading || !input.files || !input.files.length) return;
139 if (!csrf) {
140 window.alert('缺少 CSRF 令牌,请刷新页面重试');
141 return;
142 }
143 uploading = true;
144 input.disabled = true;
145 btn.disabled = true;
146 uploadQueue(Array.prototype.slice.call(input.files));
147 });
148})();