我有一个base64 PDF字符串,需要将其保存到一个文件中,以便在系统(android或ios)上打开它,我希望它位于缓存的目录中,因为在大多数情况下它只是一次性视图。
但是当我尝试通过链接打开文件时,世博会(或者可能是android)给了我关于“意图”的错误
我正在使用博览会
我收到的错误消息是:
[Error: Could not open URL 'file:///data/user/0/host.exp.exponent/cache/Despacho%20-%2000043651620108260142.pdf': file:///data/user/0/host.exp.exponent/cache/Despacho%20-%2000043651620108260142.pdf exposed beyond app through Intent.getData()]
我正在使用此函数保存并打开文件,但除了我收到的错误之外没有任何反应:
async function saveAndOpenFile(fileName: string, content: string) {
try {
let directoryUri = FileSystem.cacheDirectory + fileName;
console.log("D", directoryUri);
const writed = await FileSystem.writeAsStringAsync(directoryUri, content, { encoding: FileSystem.EncodingType.Base64 });
console.log("W", writed);
await Linking.openURL(directoryUri);
} catch (error) {
Alert.alert("Ocorreu um erro", "Não foi possível abrir o documento");
console.log(error);
}
}
我的控制台输出是:
LOG D file:///data/user/0/host.exp.exponent/cache/Despacho%20-%2000043651620108260142.pdf
LOG W null
LOG [Error: Could not open URL 'file:///data/user/0/host.exp.exponent/cache/Despacho%20-%2000043651620108260142.pdf': file:///data/user/0/host.exp.exponent/cache/Despacho%20-%2000043651620108260142.pdf exposed beyond app through Intent.getData()]
我通过这样做找到了解决方案:
const [viewUri, setViewUri] = React.useState<string | null>(null);
async function saveAndOpenFile(fileName: string, content: string) {
try {
let fileUri = FileSystem.documentDirectory + fileName;
await FileSystem.writeAsStringAsync(fileUri, content, { encoding: FileSystem.EncodingType.Base64 });
const cUri = await FileSystem.getContentUriAsync(fileUri);
if (Platform.OS === "android") {
await IntentLauncher.startActivityAsync("android.intent.action.VIEW", {
data: cUri,
flags: 1,
type: "application/pdf",
});
console.log("CLOSING NOW");
closeModal();
} else {
setViewUri(cUri); // Set as variable to display a webview below
}
} catch (error) {
Alert.alert("Ocorreu um erro", "Não foi possível abrir o documento");
console.log(error);
}
}
return (
<WebView
allowFileAccess
allowFileAccessFromFileURLs
allowUniversalAccessFromFileURLs
scalesPageToFit
mixedContentMode={Platform.OS === "android" ? "always" : undefined}
sharedCookiesEnabled={false}
originWhitelist={["http://*", "https://*", "file://*", "data:*", "content:*"]}
style={{
flex: 1,
}}
scrollEnabled={true}
source={{ uri: viewUri }}
bounces={false}
/>;
)