首页 > 解决方案 > 如何使用 expo 文件系统下载文本文件

问题描述

大家好,来自世博会网站上给出的示例:https ://docs.expo.io/versions/latest/sdk/filesystem/?redirected#downloading-files

我正在尝试下载一个 8mb 的文本文件,该文件实际上正在下载,但存在某些问题

  1. 我不知道如何处理暂停代码和恢复代码,因为它是在下载完成后调用的
  2. 我尝试根据下载进度获取百分比,但我不知道如何获取百分比,而是获取下载的千字节
  3. 最重要的是,我怎样才能让文件重新读取。下载完成后的文件路径为 file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540timotech%252Fwabpreader/Basic%20Technology%20for%20Junior%20%20Secondary%20Schools%2C%20Book %203.txt

发生错误:[未处理的承诺拒绝:TypeError:未定义不是对象(评估'FileSystem.EncodingTypes.UTF8')]

请在下面检查我的代码:

  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);
  }
};

同时,此打印输出中存在文件:

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>
 )...

感谢您的帮助,抱歉我的代码太长了

蒂姆

标签: javascriptreact-nativefilesystemsexpo

解决方案


推荐阅读