Expo FileSystem.readAsStringAsync无法读取文件

时间:2018-07-30 06:44:17

标签: reactjs react-native filesystems expo

我有以下设置,当用户使用ImagePicker拍照时,它将使用以下代码将其保存到FileSystem.documentDirectory

saveAvatar = async (uri) => {
   await Expo.FileSystem.moveAsync({
   from: uri,
   to: Expo.FileSystem.documentDirectory + 'avatar/profile'
  })
}

_takePhoto = async () => {
  const result = await ImagePicker.launchCameraAsync({
    allowsEditing: false,
    base64: true,
    quality: 0.4
  });

  if (!result.cancelled) {
    this.setState({ image: result.base64 });
    this.saveAvatar(result.uri)
  }
}; 

然后我尝试使用以下方法进行检索:

ensureDirAsync = async () => {
    const props = await FileSystem.getInfoAsync(FileSystem.documentDirectory + 'avatar/');

    if (props.exists && props.isDirectory) {
        return props;
    }

    try {
        await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + 'avatar/', { intermediates: true });
    }
    catch (e) {
        console.log(e);
    }

    return await this.ensureDirAsync()
}

getAvatar = async () => {
    let dir = await this.ensureDirAsync(),
        filename = await FileSystem.readDirectoryAsync(dir.uri),
        data = null;
    const props = await FileSystem.getInfoAsync(dir.uri + filename[0])
    console.log(props)
    try {
        data = await FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'avatar/profile');
    }
    catch (e) {
        console.log(e);
    }
    console.log(data)
    return data;
}

奇怪的是,const props = await FileSystem.getInfoAsync(dir.uri + filename[0])正在打印此内容:

Object {
 "exists": 1,
 "isDirectory": false,
 "modificationTime": 1532930978,
 "size": 399861,
 "uri": "file:///var/mobile/Containers/Data/Application/9D3661AF-8EB5-49F5-A178-3ECA0F96BEEC/Documents/ExponentExperienceData/%2540anonymous%252FWAMS-1163fc3b-4484-44a2-9076-b4b71df1e55c/avatar/profile",
} 

应该指出已成功保存图像,但是data = await FileSystem.readAsStringAsync(dir.uri + filename[0]);data = await FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'avatar/profile')会给我这个错误:

File 'file:///var/mobile/Containers/Data/Application/9D3661AF-8EB5-49F5-A178-3ECA0F96BEEC/Documents/ExponentExperienceData/%2540anonymous%252FWAMS-1163fc3b-4484-44a2-9076-b4b71df1e55c/avatar/profile' could not be read.

任何想法这怎么会发生? FileSystem.readAsStringAsync()甚至可以读取我从ImagePicker移动的文件吗?如果没有,那我应该用什么代替?

我正在IOS上尝试此操作。

提前感谢您的帮助:smiley:

2 个答案:

答案 0 :(得分:2)

明白了!事实证明,而不是使用FileSystem.moveAsync()移动文件,我只需要使用base64FileSystem.writeAsStringAsync()表示形式保存为普通字符串,就为我解决了这个问题

答案 1 :(得分:0)

您必须指定编码类型。 FileSystem.EncodingType.Base64 适用于音频/图像 文件。

示例:

content = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64 });