utils.ts 881 B

12345678910111213141516171819202122232425262728
  1. export const urlToBlob = (url: string): Promise<Blob> => {
  2. return new Promise((resolve, reject) => {
  3. const xhr = new XMLHttpRequest();
  4. xhr.open("GET", url, true);
  5. xhr.responseType = "blob";
  6. xhr.onload = function () {
  7. if (this.status === 200) {
  8. resolve(this.response as Blob); // 显式断言为 Blob 类型
  9. } else {
  10. reject(new Error("Error loading image"));
  11. }
  12. };
  13. xhr.onerror = function () {
  14. reject(new Error("Network error"));
  15. };
  16. xhr.send();
  17. });
  18. };
  19. export const urlToFile = async (url: string, fileName: string) => {
  20. console.log("urlToFile")
  21. return urlToBlob(url).then(blob => {
  22. return new File([blob], fileName, {
  23. type: blob.type,
  24. lastModified: new Date().getTime()
  25. });
  26. });
  27. }