UNPKG

@paroicms/front-media-gallery

Version:

Basic media gallery react component for Paroi CMS.

44 lines (43 loc) 1.3 kB
export function httpUpload(options) { let resolve; let reject; const promise = new Promise((resolveCb, rejectCb) => { resolve = resolveCb; reject = rejectCb; }); const xhr = new XMLHttpRequest(); xhr.addEventListener("progress", (ev) => { const progress = ev.total === 0 ? 1 : Math.round((100 * ev.loaded) / ev.total); handler.onProgress?.(progress); }); xhr.addEventListener("loadend", () => { let response; try { response = JSON.parse(xhr.response); } catch (parsingErr) { reject(new Error(`api error '${xhr.status}': ${xhr.response}`)); return; } if (xhr.status >= 200 && xhr.status < 300) { resolve(response); } else { reject(new Error(`api error '${xhr.status}': ${xhr.response}`)); } }); xhr.addEventListener("error", () => { reject(new Error(`xhr error '${xhr.status}'`)); }); xhr.addEventListener("abort", () => { reject(new Error("xhr aborted")); }); xhr.open(options.method, options.url); xhr.send(options.data); const handler = { promise, onProgress: undefined, abort: () => xhr.abort(), }; return handler; }