getFile.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. async function downloadFile(url, options) {
  2. const response = await fetch(url);
  3. if (!response.ok) throw new Error(response.statusText);
  4. const type = options.responseType || 'blob';
  5. const result = await response[type]();
  6. if (options.returnValue) {
  7. return result;
  8. }
  9. const objUrl = URL.createObjectURL(result);
  10. return { objUrl, path: url, type: result.type };
  11. }
  12. function getLocalFile(path, options) {
  13. return new Promise((resolve, reject) => {
  14. const isFile = /\.(.*)/.test(path);
  15. if (!isFile) {
  16. reject(new Error(`"${path}" is invalid file path.`));
  17. return;
  18. }
  19. const fileUrl = path?.startsWith('file://') ? path : `file://${path}`;
  20. const xhr = new XMLHttpRequest();
  21. xhr.responseType = options.responseType || 'blob';
  22. xhr.onreadystatechange = () => {
  23. if (xhr.readyState === XMLHttpRequest.DONE) {
  24. if (xhr.status === 0 || xhr.status === 200) {
  25. if (options.returnValue) {
  26. resolve(xhr.response);
  27. return;
  28. }
  29. const objUrl = URL.createObjectURL(xhr.response);
  30. resolve({ path, objUrl, type: xhr.response.type });
  31. } else {
  32. reject(new Error(xhr.statusText));
  33. }
  34. }
  35. };
  36. xhr.onerror = function () {
  37. reject(
  38. new Error(xhr.statusText || `Can't find a file with "${path}" path`)
  39. );
  40. };
  41. xhr.open('GET', fileUrl);
  42. xhr.send();
  43. });
  44. }
  45. export default function (path, options = {}) {
  46. if (path.startsWith('http')) return downloadFile(path, options);
  47. return getLocalFile(path, options);
  48. }