使用文件系统从 expo 应用程序中的 blob 生成 pdf 的问题

Problem to generate pdf from a blob in an expo app using FileSystem

我得到一个斑点,我这样对待它:

const file = response.data;
  var blob = new Blob([file], {
    type: 'application/pdf',
  });

  const fileReaderInstance = new FileReader();
  fileReaderInstance.readAsDataURL(blob);
  fileReaderInstance.onload = async () => {
    const fileUri = `${FileSystem.documentDirectory}file.pdf`;
    await FileSystem.writeAsStringAsync(
      fileUri,
      fileReaderInstance.result.split(',')[1],
      {
        encoding: FileSystem.EncodingType.Base64,
      }
    );
    console.log(fileUri);
    Sharing.shareAsync(fileUri);
  };

然而,当我生成并共享文件时,我无法访问它,如果我获得它的 URI 并在网络上搜索它 returns:

我这样解决了我的问题:

这是一个获取其他数据请求的函数,执行请求 (generate PDF()) 并处理数据并通过接收到的 blob 生成在 (fileReaderInstance.result) 上共享的缓冲区 Sharing.shareAsync()

  const generatePDF = async () => {
    setAnimating(true);
    const companyReponse = await CompanyService.getCompany();
    const peopleResponse = await PeopleService.getPerson(sale.customerId);

    const company = companyReponse.response.company;
    const people = peopleResponse.response;
    const quote = false;

    const json = await SaleService.generatePDF({
      sale,
      company,
      people,
      quote,
    });

    if (json && json.success) {
      try {
        const fileReaderInstance = new FileReader();
        fileReaderInstance.readAsDataURL(json.data);
        fileReaderInstance.onload = async () => {
          const base64data = fileReaderInstance.result.split(',');
          const pdfBuffer = base64data[1];

          const path = `${FileSystem.documentDirectory}/${sale._id}.pdf`;
          await FileSystem.writeAsStringAsync(`${path}`, pdfBuffer, {
            encoding: FileSystem.EncodingType.Base64,
          });

          await Sharing.shareAsync(path, { mimeType: 'application/pdf' });
        };
      } catch (error) {
        Alert.alert('Erro ao gerar o PDF', error.message);
      }
    }
    setAnimating(false);
  }

这是 SaleServicegeneratePDF 中的函数,它向 api 发出请求并传递 return 使用 axios 的 pdf blob 的参数:

 generatePDF: async ({ sale, company, people, quote }) => {
    const token = await AsyncStorage.getItem('token');
    const body = { sale, company, people, quote };
    try {
      const response = await axios(`${BASE_API}/generate-sale-pdf`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: token,
        },
        responseType: 'blob',
        data: body,
      });

      return {
        success: true,
        data: response.data,
      };
    } catch (err) {
      return err.error;
    }
  },