34 lines
1.1 KiB
TypeScript
34 lines
1.1 KiB
TypeScript
import type { QueueItem } from './queue';
|
|
|
|
export async function createUpload(
|
|
url: string,
|
|
it: QueueItem,
|
|
deviceId: string,
|
|
onProgress?: (percent: number) => void
|
|
): Promise<any> {
|
|
return new Promise((resolve, reject) => {
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('POST', url, true);
|
|
xhr.setRequestHeader('X-Device-Id', deviceId);
|
|
const form = new FormData();
|
|
form.append('photo', it.blob, it.fileName);
|
|
if (it.emotion_id) form.append('emotion_id', String(it.emotion_id));
|
|
if (it.task_id) form.append('task_id', String(it.task_id));
|
|
xhr.upload.onprogress = (ev) => {
|
|
if (onProgress && ev.lengthComputable) {
|
|
const pct = Math.min(100, Math.round((ev.loaded / ev.total) * 100));
|
|
onProgress(pct);
|
|
}
|
|
};
|
|
xhr.onload = () => {
|
|
if (xhr.status >= 200 && xhr.status < 300) {
|
|
try { resolve(JSON.parse(xhr.responseText)); } catch { resolve({}); }
|
|
} else {
|
|
reject(new Error('upload failed'));
|
|
}
|
|
};
|
|
xhr.onerror = () => reject(new Error('network error'));
|
|
xhr.send(form);
|
|
});
|
|
}
|