Expo FileSystem.readAsStringAsync 无法读取文件

Ray*_*han 3 filesystems reactjs react-native 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)
  }
}; 
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用以下方法检查检索它:

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;
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,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",
} 
Run Code Online (Sandbox Code Playgroud)

这应该表明图像已成功保存,但data = await FileSystem.readAsStringAsync(dir.uri + filename[0]);ORdata = 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:

小智 6

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

例子:

content = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64 });
Run Code Online (Sandbox Code Playgroud)


Ray*_*han 5

知道了!原来不是使用移动文件,FileSystem.moveAsync()我只需要base64使用普通字符串保存表示FileSystem.writeAsStringAsync(),它为我解决了问题