下面是在 iOS 的 Web 视图中使用文件的工作示例。它使用react-native-fs
npm 包使用以下命令将文件下载到本地imageUrl
变量来定义下载什么图像。我在示例中使用的 URL 指向一条小溪的自然照片。
以下示例允许指定文件夹内的所有图像baseFolderPath
以及任何嵌套文件夹内。
谨慎的做法是在两个文件之间保持相同的文件扩展名imageUrl
and imageLocalPath
变量。
import React, { useState, useEffect } from 'react';
import { Text } from 'react-native';
import { WebView } from 'react-native-webview';
import * as RNFS from 'react-native-fs';
const { DocumentDirectoryPath } = RNFS;
const getFolder = filepath => filepath.split('/').slice(0, -1).join('/');
const ensureFolderExists = folderPath => RNFS.mkdir(folderPath + '/', { NSURLIsExcludedFromBackupKey: true });
const writeFile = async (filepath, content, encoding = 'utf8') => {
await ensureFolderExists(getFolder(filepath));
await RNFS.writeFile(filepath, content, encoding);
};
const downloadFile = async (fileUrl, destinationPath) => {
await ensureFolderExists(getFolder(destinationPath));
await RNFS.downloadFile({
fromUrl: fileUrl,
toFile: destinationPath,
headers: {},
}).promise;
return destinationPath;
};
export default () => {
const baseLocalPath = `${RNFS.DocumentDirectoryPath}/myFolder`;
const htmlLocalPath = `${baseLocalPath}/webview.html`;
const imageLocalPath = `${baseLocalPath}/images/myImage.jpg`;
const imageUrl = `https://images.pexels.com/photos/3225517/pexels-photo-3225517.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2`;
const html = `<html><body><img src="${imageLocalPath}" style="width: 100%;height:100%;"></body></html>`;
const [imageDownloaded, setImageDownloaded] = useState(false);
const [htmlFileWritten, setHtmlFileWritten] = useState(false);
useEffect(() => {
writeFile(htmlLocalPath, html).then(() => setHtmlFileWritten(true));
downloadFile(imageUrl, imageLocalPath).then(() => setImageDownloaded(true));
}, []);
return (
(htmlFileWritten && imageDownloaded) ? (
<WebView
originWhitelist={['*']}
allowFileAccessFromFileURLs={true}
allowUniversalAccessFromFileURLs={true}
allowingReadAccessToURL={baseLocalPath}
source={{ uri: htmlLocalPath }}
/>
) : <Text>Loading</Text>
);
};