How to download text file using expo filesystem

Viewed 928

Good day all, From the example given at expo website: https://docs.expo.io/versions/latest/sdk/filesystem/?redirected#downloading-files

I'm trying to download an 8mb text file, which is actually downloading, but with certain issues

  1. I don't know how to handle the pause code and resume code, because it is being called after the download finishes
  2. I try to get the percentage based on the download progress, but I don't know how to get the percentage, instead i'm getting the downloaded kilobytes
  3. Most important, how can i get the file back to read from it. The file path after download finishes is file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540timotech%252Fwabpreader/Basic%20Technology%20for%20Junior%20%20Secondary%20Schools%2C%20Book%203.txt

Error occurs: [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'FileSystem.EncodingTypes.UTF8')]

Please check my code below:

  componentDidMount() {
     this.downloadEbook();
  }

  downloadEbook = async () => {
    //Get download progress
    const callback = (downloadProgress) => {
    const progress =
      downloadProgress.totalBytesWritten /
      downloadProgress.totalBytesExpectedToWrite;
    this.setState({
      downloadProgress: progress, //showing in kilobytes
    });
    console.log(progress);
  };

  //Gets the text file
  const downloadResumable = FileSystem.createDownloadResumable(
    "http://books.timotechng.com/images/compressed/Basic Technology for Junior  Secondary Schools, 
    Book 3.txt",
    FileSystem.documentDirectory +
      "Basic Technology for Junior  Secondary Schools, Book 3.txt",
    {},
    callback
  );

  try {
    this.setState({ isLoading: true }); //shows activityindicator while download is going on
    const { uri } = await downloadResumable.downloadAsync();
    console.log("Finished downloading to ", uri);
    this.setState({ isLoading: false });
  } catch (e) {
    console.error(e);
  }

  //I don't know how to handle this, its being called after download finishes
  try {
    await downloadResumable.pauseAsync();
    console.log("Paused download operation, saving for future retrieval");
    AsyncStorage.setItem(
      "pausedDownload",
      JSON.stringify(downloadResumable.savable())
    );
  } catch (e) {
    console.error(e);
  }

  //I don't know how to handle this, its being called after download finishes
  try {
    const { uri } = await downloadResumable.resumeAsync();
    console.log("Finished downloading to ", uri);
  } catch (e) {
    console.error(e);
  }
};


//Code to get the file after download
 readEbook = async () => {
   // const filePath = this.state.filePath;
   // const assetInfo = await MediaLibrary.getAssetInfoAsync(filePath);
   // console.log(assetInfo);

  let tmp = await FileSystem.getInfoAsync(
    FileSystem.documentDirectory +
      "Basic Technology for Junior  Secondary Schools, Book 3.txt"
  );
  if (tmp.exists) {
    console.log("file exists");
    console.log(tmp);
    //let filename = FileSystem.documentDirectory + "userData.txt";
    let file = await FileSystem.readAsStringAsync(tmp.uri, {
      encoding: FileSystem.EncodingTypes.UTF8,
    });
    //Error occurs here: [Unhandled promise rejection: TypeError: undefined is not an object 
 (evaluating 'FileSystem.EncodingTypes.UTF8')]
    console.log("file", file);
  }
};

Meanwhile file exists from this print out:

file exists
Object {
  "exists": true,
  "isDirectory": false,
  "modificationTime": 1611246702,
  "size": 8744195,  
  "uri":

"file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540timotech%252Fwabpreader/Basic%20Technology%20for%20Junior%20%20Secondary%20Schools%2C%20Book%203.txt", }

//Display of percentage
 return this.state.isLoading ? (
   <View style={{ marginTop: 20 }}>
     <ActivityIndicator
       size="large"
       color="#00ff00"
       animating={this.state.isLoading}
     />
     <Text style={{ justifyContent: "center", textAlign: "center" }}>
       Downloading file for first time use at {this.state.downloadProgress}%
     </Text>
   </View>
 )...

Thanks for your help, sorry my codes are so long

Tim

0 Answers
Related