Expo文档选取器未返回正确的uri



所以我正在尝试使用expo文档选择器(https://docs.expo.io/versions/latest/sdk/document-picker/)让用户从他们的手机文件系统中选择图像并将其显示在屏幕上。它最近一直在工作,直到我注意到它发送回的promise停止返回正确的uri。之前它返回了一个以file:///data/开头的uri,现在它返回了以/data开头的uri。这种新型的uri不会显示在屏幕上,我想知道如何回到旧的?我首先使用await DocumentPicker.getDocumentAsync来获取文件。

从expo 38升级到42后,我遇到了完全相同的问题。我用expo-file-system做了一个变通办法。

首先,我将copyToCacheDirectory选项设置为假

const result = await DocumentPicker.getDocumentAsync({
type:'*/*',
copyToCacheDirectory: false,
});

这将把文件保存到conten://文件空间中。一旦我们有了文件,我们就可以将其复制到我们的file://位置:

const uri = FileSystem.documentDirectory+result.name;
await FileSystem.copyAsync({
from: result.uri,
to: uri
})

现在,您应该能够毫无问题地使用uri(包括文件://路径(。

我从expo SDK 38到SDK 42都有同样的问题,
我从这里找到了一个解决方法

const encode = uri => {
if (Platform.OS === 'android') return encodeURI(`file://${uri}`)
else return uri
}
...
<Button 
onPress = { async () => {
let result = await DocumentPicker.getDocumentAsync({ type: '*/*' })
if (result.type === "success") {
console.log("getDocumentAsync", result);
Alert.alert(
"upload file",
`Whether to upload ${result.name}`,
[
{
text: "Cancel",
onPress: () => {},
style: "cancel"
},
{ 
text: "OK", 
onPress: () => dispatch(action.sendFile(encode(result.uri))) 
}
],
{ cancelable: true }
)
}
}}
/>

它对我有用!

如果你想在WebView中使用该文件,你可以执行

const result = await DocumentPicker.getDocumentAsync({
type: "application/pdf",
copyToCacheDirectory: false,
});

这将给你一个类似的uri

{
...,
"uri": "content://com.android.externalstorage.documents/document/home%3Ayour-file.pdf",
}

您可以通过将其作为uri 传递来访问该文件

{{
uri: uri,
}}

最新更新