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

Expo FileSystem iconExpo FileSystem

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

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

expo-file-system 提供对存储在设备上或作为资源打包到本地项目中的文件和目录的访问。它还允许从网络下载文件。

安装

🌐 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.

应用配置中的配置

🌐 Configuration in app config

如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 配置插件 来配置 expo-file-system。该插件允许你配置无法在运行时设置并且需要构建新的应用二进制文件才能生效的各种属性。如果你的应用不使用 CNG,则需要手动配置该库。

🌐 You can configure expo-file-system using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-file-system", { "supportsOpeningDocumentsInPlace": true, "enableFileSharing": true } ] ] } }

Configurable properties

NameDefaultDescription
supportsOpeningDocumentsInPlacefalse
Only for: 
iOS

A boolean to enable LSSupportsOpeningDocumentsInPlace in Info.plist. This allows the app to open documents in place.

enableFileSharingfalse
Only for: 
iOS

A boolean to enable UIFileSharingEnabled in Info.plist. This enables file sharing in the iOS Files app, making the app's Documents directory accessible to users through the Files app, iTunes File Sharing, and other file management tools.

Are you using this library in an existing React Native app?

如果你没有使用连续原生生成(CNG),或者你是手动使用原生 iOS 项目,那么你需要将 LSSupportsOpeningDocumentsInPlace 和 UIFileSharingEnabled 键添加到你项目的 ios/[app]/Info.plist 中:

🌐 If you're not using Continuous Native Generation (CNG) or you're using native ios project manually, then you need to add the LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled keys to your project's ios/[app]/Info.plist:

<key>LSSupportsOpeningDocumentsInPlace</key> <true/> <key>UIFileSharingEnabled</key> <true/>

用法

🌐 Usage

import { File, Directory, Paths } from 'expo-file-system';

File 和 Directory 实例保存对文件、内容或资源 URI 的引用。

🌐 The File and Directory instances hold a reference to a file, content, or asset URI.

文件或目录不需要存在——只有在使用错误的类来表示已存在的路径时,构造函数才会抛出错误(例如,如果你尝试创建一个 File 实例,并传入一个已存在目录的路径)。

🌐 The file or directory does not need to exist — an error will be thrown from the constructor only if the wrong class is used to represent an existing path (so if you try to create a File instance passing a path to an already existing directory).

特性

🌐 Features

  • 同步和异步,对文件内容的读写访问
  • 创建、修改和删除
  • 可用属性,如 type、size、creationDate 等
  • 能够以流的方式或使用 FileHandle 类读取和写入文件
  • 使用 downloadFileAsync 或 expo/fetch 轻松下载/上传文件
  • 使用平台原生流程预览文件

示例

🌐 Examples

写入和读取文本文件
example.ts
import { File, Paths } from 'expo-file-system'; try { const file = new File(Paths.cache, 'example.txt'); file.create(); // can throw an error if the file already exists or no permission to create it await file.write('Hello, world!'); // or `file.writeSync('Hello, world!');` for synchronous call console.log(file.textSync()); // Hello, world! } catch (error) { console.error(error); }
使用系统选择器选择文件

expo-document-picker 的用法:

🌐 Usage with expo-document-picker:

example.ts
import { File } from 'expo-file-system'; import * as DocumentPicker from 'expo-document-picker'; try { const result = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true }); if (!result.canceled) { const { uri } = result.assets[0]; const file = new File(uri); console.log(file.textSync()); } } catch (error) { console.error(error); }

在 Android 上使用内置的 pickFileAsync 或 pickDirectoryAsync 方法:

🌐 Using the built-in pickFileAsync or pickDirectoryAsync method on Android:

example.ts
import { File } from 'expo-file-system'; try { const file = new File.pickFileAsync(); console.log(file.textSync()); } catch (error) { console.error(error); }
正在下载文件

使用 downloadFileAsync:

🌐 Using downloadFileAsync:

example.ts
import { Directory, File, Paths } from 'expo-file-system'; const url = 'https://pdfobject.com/pdf/sample.pdf'; const destination = new Directory(Paths.cache, 'pdfs'); try { destination.create(); const output = await File.downloadFileAsync(url, destination); console.log(output.exists); // true console.log(output.uri); // path to the downloaded file, e.g., '${cacheDirectory}/pdfs/sample.pdf' } catch (error) { console.error(error); }

或者使用 expo/fetch:

🌐 Or using expo/fetch:

example.ts
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const url = 'https://pdfobject.com/pdf/sample.pdf'; const response = await fetch(url); const src = new File(Paths.cache, 'file.pdf'); await src.write(await response.bytes());
预览文件

使用 File.preview() 在本地查看器中打开本地文件。Android 会打开支持该文件 MIME 类型的已安装应用。iOS 则使用快速预览(Quick Look)。

🌐 Use File.preview() to open local files in the native viewer. Android opens an installed app that supports the file's MIME type. iOS uses Quick Look.

File.preview() 和 File.canPreview() 接受 File 或有序的 File[]。 对于单个文件,你也可以直接调用 file.preview() 和 file.canPreview()。

example.ts
import { File, Paths } from 'expo-file-system'; const file = await File.downloadFileAsync( 'https://pdfobject.com/pdf/sample.pdf', new File(Paths.cache, 'sample.pdf') ); if (await File.canPreview(file)) { await File.preview(file, { title: 'Sample PDF' }); }

多文件仅在 iOS 上支持。 这个示例会先打开注意,然后让用户浏览 PDF:

example.ts
const notes = new File(Paths.cache, 'notes.txt'); await notes.write('Notes about the PDF'); const files = [file, notes]; if (await File.canPreview(files)) { await File.preview(files, { initialIndex: 1 }); }

initialIndex 是从零开始的,默认值是 0。一个文件的数组在两个平台上都可以使用。在 Android 上,传递多个文件会导致 File.canPreview() 解析为 false,而 File.preview() 会被拒绝。

File.preview() 如果你用多个文件传入 title 或 mimeType 会拒绝。 File.canPreview() 如果你用多个文件传入 mimeType 也会拒绝。 对于单个文件,mimeType 默认使用文件的 type。如果扩展名不能识别类型,尤其是在 Android 上,请明确传入。

File.canPreview() 在平台无法预览,或者已检查的文件丢失或类型不受支持时会解析为 false。如果遇到无效或无法读取的文件,它会拒绝。File.preview() 如果任何文件无法预览或 initialIndex 无效也会拒绝。这两种方法都会拒绝空数组。

在查看器关闭之前保持文件可用。File.preview() 在预览展示或交给其他应用时解决。

🌐 Keep files available until the viewer closes. File.preview() resolves when the preview is presented or handed off to another app.

如果在你的应用中分享表很有用,当预览失败时,你可以用 expo-sharing 来组合它:

🌐 If a share sheet is useful in your app, you can compose this with expo-sharing when previewing fails:

example.ts
import { File, Paths } from 'expo-file-system'; import * as Sharing from 'expo-sharing'; // This can be a file created, picked, or downloaded earlier. const file = new File(Paths.cache, 'report.pdf'); try { await file.preview({ title: 'Report' }); } catch { if (await Sharing.isAvailableAsync()) { await Sharing.shareAsync(file.uri, { dialogTitle: 'Share report', mimeType: file.type || 'application/pdf', }); } }
使用 expo/fetch上传文件

你可以使用内置在 Expo 包中的 fetch 直接以 blob 形式上传文件:

🌐 You can upload files as blobs directly with fetch built into the Expo package:

example.ts
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const file = new File(Paths.cache, 'file.txt'); await file.write('Hello, world!'); const response = await fetch('https://example.com', { method: 'POST', body: file, });

或者使用 FormData 构造函数:

🌐 Or using the FormData constructor:

example.ts
import { fetch } from 'expo/fetch'; import { File, Paths } from 'expo-file-system'; const file = new File(Paths.cache, 'file.txt'); await file.write('Hello, world!'); const formData = new FormData(); formData.append('data', file); const response = await fetch('https://example.com', { method: 'POST', body: formData, });
移动和复制文件
example.ts
import { Directory, File, Paths } from 'expo-file-system'; try { const file = new File(Paths.document, 'example.txt'); file.create(); console.log(file.uri); // '${documentDirectory}/example.txt' const copiedFile = new File(Paths.cache, 'example-copy.txt'); file.copy(copiedFile); console.log(copiedFile.uri); // '${cacheDirectory}/example-copy.txt' file.move(Paths.cache); console.log(file.uri); // '${cacheDirectory}/example.txt' file.move(new Directory(Paths.cache, 'newFolder')); console.log(file.uri); // '${cacheDirectory}/newFolder/example.txt' } catch (error) { console.error(error); }
使用 FileHandle 的随机访问读取

使用 FileHandle 可以高效、随机访问大文件而无需将整个文件加载到内存中。通过调用 file.open() 获取一个句柄,使用 offset 属性在任意位置进行读取或写入,完成后记得关闭句柄。

🌐 Use FileHandle for efficient, random-access reads of large files without loading the entire file into memory. Obtain a handle by calling file.open(), read or write at any position using the offset property, and always close the handle when finished.

example.ts
import { File, Paths, FileMode } from 'expo-file-system'; const file = new File(Paths.document, 'recording.wav'); const handle = file.open(FileMode.ReadOnly); // Read the WAV header (first 44 bytes) const header = handle.readBytesSync(44); const sampleRate = new DataView(header.buffer).getUint32(24, true); console.log(`Sample rate: ${sampleRate} Hz`); // Seek to a specific offset and read a chunk handle.offset = 1024; const chunk = await handle.readBytes(4096); console.log(`Read ${chunk.length} bytes from offset 1024`); // Read an entire file in 64 KB chunks handle.offset = 0; const CHUNK_SIZE = 64 * 1024; while (handle.offset! < handle.size!) { const data = await handle.readBytes(CHUNK_SIZE); // Process data... } handle.close();
使用传统文件系统 API
example.ts
import * as FileSystem from 'expo-file-system/legacy'; import { File, Paths } from 'expo-file-system'; try { const file = new File(Paths.cache, 'example.txt'); const content = await FileSystem.readAsStringAsync(file.uri); console.log(content); } catch (error) { console.error(error); }
递归列出目录内容
example.ts
import { Directory, Paths } from 'expo-file-system'; function printDirectory(directory: Directory, indent: number = 0) { console.log(`${' '.repeat(indent)} + ${directory.name}`); const contents = directory.list(); for (const item of contents) { if (item instanceof Directory) { printDirectory(item, indent + 2); } else { console.log(`${' '.repeat(indent + 2)} - ${item.name} (${item.size} bytes)`); } } } try { printDirectory(new Directory(Paths.cache)); } catch (error) { console.error(error); }

应用接口

🌐 API

No API data file found, sorry!