0

我从 api 接收一个 blob,我想将它作为 pdf 文档保存到文件系统。但是在保存时,我在我的手机中得到一个大小为 0B 的文件

代码

export const getParkingReciept = (bookindId) => {
   
     return async function (dispatch, getState) {

      try {
    const TOKEN = getState().Auth.token;

    const formdata = new FormData();
  formdata.append("booking_id", bookindId);


    RNFetchBlob.fetch(
        'POST',
        `${BASE_URL}parking-space/booking/receipt`,
        { 
            'Accept': 'application/json',
            'Authorization': `Bearer ${TOKEN}`,
            'Content-Type': 'multipart/form-data'
        },[

            { name : 'booking_id',  data: bookindId.toString()}
          ]
    )
    .then(
        response => {
            console.log("response is ",response);
        response.blob().then(res=>console.log(checkPermission(res,response.taskId)));
       console.log("pdf base64 is ", response.base64());

 }
    ).catch((error) => {
        // error handling
        console.log("Error", error)
    }
    
    
    );
    
}catch (e) {
    if (e.response) {
        console.log("error response is ", e.response);
    } else if (e.request) {
        console.log(e.request);
    } else {
        console.log('Error', e);
    }
    console.log(e.config);
}
}    
const checkPermission=async (file,name) => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: "Cool Photo App Camera Permission",
          message:
            "Cool Photo App needs access to your camera " +
            "so you can take awesome pictures.",
          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK"
        }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can write to external storage");
        var path = RNFS.DownloadDirectoryPath + '/'+name+".pdf";
console.log("pdf being written is ",file);

        RNFS.writeFile(path,  file, 'utf8')
        .then((success) => {
          console.log('FILE WRITTEN!');
          RNFetchBlob.fs.scanFile([ { path : path, mime : "application/pdf" } ])
          //     .then(() => {
          //       console.log("scan file success")
          //     })
          //     .catch((err) => {
          //       console.log("scan file error")
          //     })
        })
        .catch((err) => {
          console.log(err.message);
        });
      } else {
        console.log("permission denied");
      }
    } catch (err) {
      console.warn(err);
    }
  };

我从 fetch 得到的回应是 在此处输入图像描述

在调用响应的 blob() 函数时,我得到的是在此处输入图像描述

那里有 Application/pdf 类型,但在 base 64 字符串中,它不以 JVBERi 开头,它以一些 SFRUU 开头,这是一个有效的 pdf 文件吗?我错过了什么?我在这里做错了什么?

4

1 回答 1

0

这个答案解决了您的问题,详细解释了如何使用 rn fetch blob 从网络请求中下载文件

https://stackoverflow.com/a/56890611/7324484

下载文件后,也可以使用直接打开 pdf

https://www.npmjs.com/package/react-native-pdf

于 2021-06-16T21:28:39.530 回答