request.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { __awaiter } from "tslib";
  2. /**
  3. * 文件下载并获取下载进度
  4. */
  5. export const requestWithPercent = ({ url = "", option = {}, onProcess, }) => __awaiter(void 0, void 0, void 0, function* () {
  6. var _a;
  7. const res = yield fetch(url, Object.assign({ mode: "cors", headers: {
  8. responseType: "arraybuffer",
  9. Accept: "application/json, text/plain, */*",
  10. "Cache-Control": "no-cache",
  11. } }, option));
  12. const reader = (_a = res.body) === null || _a === void 0 ? void 0 : _a.getReader();
  13. /** 文件总长度 */
  14. const contentLength = Number(res.headers.get("content-length"));
  15. const chunks = [];
  16. let receivedLength = 0;
  17. if (!reader)
  18. return Promise.reject(new Error("无法解析请求体"));
  19. while (true) {
  20. const { done, value } = yield reader.read();
  21. if (done) {
  22. break;
  23. }
  24. chunks.push(value);
  25. receivedLength += value.length;
  26. onProcess(receivedLength, contentLength);
  27. }
  28. const chunksAll = new Uint8Array(receivedLength);
  29. let position = 0;
  30. for (const chunk of chunks) {
  31. chunksAll.set(chunk, position);
  32. position += chunk.length;
  33. }
  34. return chunksAll;
  35. });