({
target,
body,
fileName,
onProgress,
}: {
target: UploadTarget;
body: Blob;
fileName?: string;
onProgress?: (progress: UploadProgress) => void;
})
| 23 | "type" in target && target.type === "driveResumable"; |
| 24 | |
| 25 | export function uploadWithTarget({ |
| 26 | target, |
| 27 | body, |
| 28 | fileName, |
| 29 | onProgress, |
| 30 | }: { |
| 31 | target: UploadTarget; |
| 32 | body: Blob; |
| 33 | fileName?: string; |
| 34 | onProgress?: (progress: UploadProgress) => void; |
| 35 | }) { |
| 36 | return new Promise<void>((resolve, reject) => { |
| 37 | const xhr = new XMLHttpRequest(); |
| 38 | |
| 39 | if (isPostTarget(target)) { |
| 40 | const formData = new FormData(); |
| 41 | Object.entries(target.fields).forEach(([key, value]) => { |
| 42 | formData.append(key, value); |
| 43 | }); |
| 44 | formData.append("file", body, fileName); |
| 45 | xhr.open("POST", target.url); |
| 46 | xhr.upload.onprogress = (event) => { |
| 47 | if (event.lengthComputable) { |
| 48 | onProgress?.({ loaded: event.loaded, total: event.total }); |
| 49 | } |
| 50 | }; |
| 51 | xhr.onload = () => { |
| 52 | if (xhr.status >= 200 && xhr.status < 300) { |
| 53 | resolve(); |
| 54 | } else { |
| 55 | reject(new Error(`Upload failed with status ${xhr.status}`)); |
| 56 | } |
| 57 | }; |
| 58 | xhr.onerror = () => reject(new Error("Upload failed")); |
| 59 | xhr.send(formData); |
| 60 | return; |
| 61 | } |
| 62 | |
| 63 | xhr.open("PUT", target.url); |
| 64 | Object.entries(target.headers).forEach(([key, value]) => { |
| 65 | xhr.setRequestHeader(key, value); |
| 66 | }); |
| 67 | if (isDriveResumableTarget(target) && body.size > 0) { |
| 68 | xhr.setRequestHeader( |
| 69 | "Content-Range", |
| 70 | `bytes 0-${body.size - 1}/${body.size}`, |
| 71 | ); |
| 72 | } |
| 73 | xhr.upload.onprogress = (event) => { |
| 74 | if (event.lengthComputable) { |
| 75 | onProgress?.({ loaded: event.loaded, total: event.total }); |
| 76 | } |
| 77 | }; |
| 78 | xhr.onload = () => { |
| 79 | if (xhr.status >= 200 && xhr.status < 300) { |
| 80 | resolve(); |
| 81 | } else { |
| 82 | reject(new Error(`Upload failed with status ${xhr.status}`)); |
no test coverage detected