Untitled

 avatar
unknown
typescript
3 months ago
1.9 kB
9
Indexable
const downloadToCache = async (url: string) => {
    try {
      const { dirs } = ReactNativeBlobUtil.fs;

      // 1. Tải file về thư mục tạm (chưa cần biết tên file)
      const res = await ReactNativeBlobUtil.config({
        fileCache: true, // Để thư viện tự quản lý file tạm
        appendExt: "pdf" // Có thể thêm đuôi mặc định nếu muốn
      }).fetch("GET", url);

      // 2. Lấy header từ phản hồi của server
      const headers = res.info().headers;
      const contentDisposition =
        headers["Content-Disposition"] || headers["content-disposition"];

      let fileName = "document.pdf"; // Tên mặc định

      if (contentDisposition) {
        // Dùng regex để trích xuất filename từ header (đây là tiêu chuẩn HTTP)
        const match = contentDisposition.match(
          /filename=(?:"([^"]+)"|([^;]+))/
        );
        if (match) {
          fileName = match[1] || match[2];
        }
      }

      const currentPath = res.path(); // Đường dẫn file tạm hiện tại
      const newPath = `${dirs.CacheDir}/${fileName}`; // Đường dẫn mới với tên chuẩn

      // 3. Di chuyển/Đổi tên file tạm sang tên thật
      await ReactNativeBlobUtil.fs.mv(currentPath, newPath);

      console.log("File đã được lưu tại:", newPath);

      if (isAndroid) {
        // Code xử lý cho Android (ví dụ dùng MediaScanner để hiện trong Download)
        // Hoặc đơn giản là dùng Share tương tự iOS
        showToast({ type: "success", title: `Đã tải: ${fileName}` });
      } else {
        await Share.open({
          url: `file://${newPath}`, // Thêm file:// cho iOS
          type: "application/pdf",
          saveToFiles: true
        });
      }
    } catch (error) {
      console.log("Lỗi:", error);
      return null;
    }
  };
Editor is loading...
Leave a Comment