Add files via upload

This commit is contained in:
公明
2026-03-29 03:24:22 +08:00
committed by GitHub
parent 324ac638d9
commit e0c9a3bd8e
7 changed files with 330 additions and 46 deletions
+48
View File
@@ -163,6 +163,54 @@ async function apiFetch(url, options = {}) {
return response;
}
/**
* multipart POST with XMLHttpRequest so upload progress is available (fetch 无法可靠上报进度).
* 返回与 fetch 类似的对象:ok、status、json()、text()
*/
async function apiUploadWithProgress(url, formData, options = {}) {
await ensureAuthenticated();
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
if (authToken) {
xhr.setRequestHeader('Authorization', `Bearer ${authToken}`);
}
xhr.upload.onprogress = (e) => {
if (!onProgress || !e.lengthComputable) return;
const percent = e.total > 0 ? Math.round((e.loaded / e.total) * 100) : 0;
onProgress({ loaded: e.loaded, total: e.total, percent });
};
xhr.onerror = () => {
reject(new Error('Network error'));
};
xhr.onload = () => {
if (xhr.status === 401) {
handleUnauthorized();
const msg = (typeof window !== 'undefined' && typeof window.t === 'function')
? window.t('auth.unauthorized')
: '未授权访问';
reject(new Error(msg));
return;
}
const responseText = xhr.responseText || '';
resolve({
ok: xhr.status >= 200 && xhr.status < 300,
status: xhr.status,
text: async () => responseText,
json: async () => {
try {
return responseText ? JSON.parse(responseText) : {};
} catch (err) {
throw err;
}
},
});
};
xhr.send(formData);
});
}
async function submitLogin(event) {
event.preventDefault();
const passwordInput = document.getElementById('login-password');