This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo 文件系统(遗留) iconExpo 文件系统(遗留)

提供对设备上本地文件系统的访问的库。

Android
iOS
tvOS
Included in Expo Go
Recommended version:
~58.0.8

expo-file-system 提供对存储在设备本地的文件系统的访问。它还能够从网络 URL 上传和下载文件。

说明 expo-file-system 如何与不同资源交互的图表
expo-file-system 在 Expo Go 应用中是如何不同工作的

Within Expo Go, each project has a separate file system scope and has no access to the file system of other projects.

安装

🌐 Installation

Terminal
- npx expo install expo-file-system
- yarn expo install expo-file-system
- pnpm expo install expo-file-system
- bun expo install expo-file-system

If you are installing this in an existing React Native app, make sure to install expo in your project.

用法

🌐 Usage

正在下载文件

🌐 Downloading files

Component.js
const callback = downloadProgress => { const progress = downloadProgress.totalBytesWritten / downloadProgress.totalBytesExpectedToWrite; this.setState({ downloadProgress: progress, }); }; const downloadResumable = FileSystem.createDownloadResumable( 'https://example.com/videos/small.mp4', FileSystem.documentDirectory + 'small.mp4', {}, callback ); try { const { uri } = await downloadResumable.downloadAsync(); console.log('Finished downloading to ', uri); } catch (e) { console.error(e); } try { await downloadResumable.pauseAsync(); console.log('Paused download operation, saving for future retrieval'); AsyncStorage.setItem('pausedDownload', JSON.stringify(downloadResumable.savable())); } catch (e) { console.error(e); } try { const { uri } = await downloadResumable.resumeAsync(); console.log('Finished downloading to ', uri); } catch (e) { console.error(e); } //To resume a download across app restarts, assuming the DownloadResumable.savable() object was stored: const downloadSnapshotJson = await AsyncStorage.getItem('pausedDownload'); const downloadSnapshot = JSON.parse(downloadSnapshotJson); const downloadResumable = new FileSystem.DownloadResumable( downloadSnapshot.url, downloadSnapshot.fileUri, downloadSnapshot.options, callback, downloadSnapshot.resumeData ); try { const { uri } = await downloadResumable.resumeAsync(); console.log('Finished downloading to ', uri); } catch (e) { console.error(e); }

管理 Giphy

🌐 Managing Giphy's

Giphy example
import * as FileSystem from 'expo-file-system/legacy'; const gifDir = FileSystem.cacheDirectory + 'giphy/'; const gifFileUri = (gifId: string) => gifDir + `gif_${gifId}_200.gif`; const gifUrl = (gifId: string) => `https://media1.giphy.com/media/${gifId}/200.gif`; // Checks if gif directory exists. If not, creates it async function ensureDirExists() { const dirInfo = await FileSystem.getInfoAsync(gifDir); if (!dirInfo.exists) { console.log("Gif directory doesn't exist, creating…"); await FileSystem.makeDirectoryAsync(gifDir, { intermediates: true }); } } // Downloads all gifs specified as array of IDs export async function addMultipleGifs(gifIds: string[]) { try { await ensureDirExists(); console.log('Downloading', gifIds.length, 'gif files…'); await Promise.all(gifIds.map(id => FileSystem.downloadAsync(gifUrl(id), gifFileUri(id)))); } catch (e) { console.error("Couldn't download gif files:", e); } } // Returns URI to our local gif file // If our gif doesn't exist locally, it downloads it export async function getSingleGif(gifId: string) { await ensureDirExists(); const fileUri = gifFileUri(gifId); const fileInfo = await FileSystem.getInfoAsync(fileUri); if (!fileInfo.exists) { console.log("Gif isn't cached locally. Downloading…"); await FileSystem.downloadAsync(gifUrl(gifId), fileUri); } return fileUri; } // Exports shareable URI - it can be shared outside your app export async function getGifContentUri(gifId: string) { return FileSystem.getContentUriAsync(await getSingleGif(gifId)); } // Deletes whole giphy directory with all its content export async function deleteAllGifs() { console.log('Deleting all GIF files…'); await FileSystem.deleteAsync(gifDir); }

服务器:处理多部分请求

🌐 Server: handling multipart requests

Node.js 中的简单服务器,可以将上传的图片保存到磁盘:

🌐 The simple server in Node.js, which can save uploaded images to disk:

index.js
const express = require('express'); const app = express(); const fs = require('fs'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); // This method will save the binary content of the request as a file. app.patch('/binary-upload', (req, res) => { req.pipe(fs.createWriteStream('./uploads/image' + Date.now() + '.png')); res.end('OK'); }); // This method will save a "photo" field from the request as a file. app.patch('/multipart-upload', upload.single('photo'), (req, res) => { // You can access other HTTP parameters. They are located in the body object. console.log(req.body); res.end('OK'); }); app.listen(3000, () => { console.log('Working on port 3000'); });

应用接口

🌐 API

import * as FileSystem from 'expo-file-system/legacy';

目录

🌐 Directories

该 API 使用指向设备上本地文件的 file:// URI 来识别文件。每个应用只能对以下目录下的位置进行读写访问:

🌐 The API takes file:// URIs pointing to local files on the device to identify files. Each app only has read and write access to locations under the following directories:

例如,位于应用用户文档目录下名为 'myDirectory' 的文件 'myFile' 的 URI 将是 FileSystem.documentDirectory + 'myDirectory/myFile'。

🌐 So, for example, the URI to a file named 'myFile' under 'myDirectory' in the app's user documents directory would be FileSystem.documentDirectory + 'myDirectory/myFile'.

创建文件的 Expo API 通常在这些目录中操作。这包括 Audio 录音、Camera 照片、ImagePicker 结果、SQLite 数据库和 takeSnapShotAsync() 结果。这允许它们与 FileSystem API 一起使用。

🌐 Expo APIs that create files generally operate within these directories. This includes Audio recordings, Camera photos, ImagePicker results, SQLite databases and takeSnapShotAsync() results. This allows their use with the FileSystem API.

一些 FileSystem 函数能够从其他位置读取数据(但不能写入)。

🌐 Some FileSystem functions are able to read from (but not write to) other locations.

SAF 统一资源标识符

🌐 SAF URI

SAF URI 是与存储访问框架兼容的 URI。它应该看起来像这样 content://com.android.externalstorage.*。 获得这种 URI 的最简单方法是通过 requestDirectoryPermissionsAsync 方法。

🌐 A SAF URI is a URI that is compatible with the Storage Access Framework. It should look like this content://com.android.externalstorage.*. The easiest way to obtain such URI is by requestDirectoryPermissionsAsync method.

No API data file found, sorry!

支持的 URI 方案

🌐 Supported URI schemes

在这张表中,你可以看到每种方法可以处理哪种类型的 URI。例如,如果你有一个以 content:// 开头的 URI,你不能使用 FileSystem.readAsStringAsync(),但可以使用支持该方案的 FileSystem.copyAsync()。

🌐 In this table, you can see what type of URI can be handled by each method. For example, if you have an URI, which begins with content://, you cannot use FileSystem.readAsStringAsync(), but you can use FileSystem.copyAsync() which supports this scheme.

方法名称安卓iOS
getInfoAsyncfile:///,
content://,
asset://,
无方案
file://,
ph://,
assets-library://
readAsStringAsyncfile:///,
asset://,
SAF URI
file://
writeAsStringAsyncfile:///,
SAF URI
file://
deleteAsyncfile:///,
SAF URI
file://
moveAsync来源:
file:///,
SAF URI

目的地:
file://
来源:
file://

目的地:
file://
copyAsync来源:
file:///,
content://,
asset://,
SAF URI,
无方案

目的地:
file://
来源:
file://,
ph://,
assets-library://

目的地:
file://
makeDirectoryAsyncfile:///file://
readDirectoryAsyncfile:///file://
downloadAsync来源:
http://,
https://

目的地:
file:///
来源:
http://,
https://

目的地:
file://
uploadAsync来源:
file:///

目的地:
http://
https://
来源:
file://

目的地:
http://
https://
createDownloadResumable来源:
http://,
https://

目的地:
file:///
来源:
http://,
https://

目的地:
file://

权限

🌐 Permissions

安卓

🌐 Android

通过此库的 AndroidManifest.xml 会自动添加以下权限。

🌐 The following permissions are added automatically through this library's AndroidManifest.xml.

Android permissionDescription

READ_EXTERNAL_STORAGE

Allows an application to read from external storage.

WRITE_EXTERNAL_STORAGE

Allows an application to write to external storage.

INTERNET

Allows applications to open network sockets.

iOS

无需权限。

🌐 No permissions required.