expo-file-system
provides access to a file system stored locally on the device. Within the Expo client, each app has a separate file system and has no access to the file system of other Expo apps. However, it can save content shared by other apps to local filesystem, as well as share local files to other apps. It is also capable of uploading and downloading files from network URLs.Android Device | Android Emulator | iOS Device | iOS Simulator | Web |
---|---|---|---|---|
expo install expo-file-system
If you're installing this in a bare React Native app, you should also follow these additional installation instructions.
READ_EXTERNAL_STORAGE
, WRITE_EXTERNAL_STORAGE
and INTERNET
permissions are automatically added.const callback = downloadProgress => { const progress = downloadProgress.totalBytesWritten / downloadProgress.totalBytesExpectedToWrite; this.setState({ downloadProgress: progress, }); }; const downloadResumable = FileSystem.createDownloadResumable( 'http://techslides.com/demos/sample-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 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); }
import * as FileSystem from 'expo-file-system'; 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); }
import * as FileSystem from 'expo-file-system';
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:file://
URI pointing to the directory where user documents for this app will be stored. Files stored here will remain until explicitly deleted by the app. Ends with a trailing /
. Example uses are for files the user saves that they expect to see again.file://
URI pointing to the directory where temporary files used by this app will be stored. Files stored here may be automatically deleted by the system when low on storage. Example uses are for downloaded or generated files that the app just needs for one-time usage.'myFile'
under 'myDirectory'
in the app's user documents directory would be FileSystem.documentDirectory + 'myDirectory/myFile'
.Audio
recordings, Camera
photos, ImagePicker
results, SQLite
databases and takeSnapShotAsync()
results. This allows their use with the FileSystem
API.FileSystem
functions are able to read from (but not write to) other locations. Currently FileSystem.getInfoAsync()
and FileSystem.copyAsync()
are able to read from URIs returned by CameraRoll.getPhotos()
from React Native.Note: The background session doesn't fail if the server or your connection is down. Rather, it continues retrying until the task succeeds or is canceled manually.
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'); });
CameraRoll.getPhotos()
. See supported URI schemes.false
by default.CameraRoll.getPhotos()
(skipping this can prevent downloading the file if it's stored in iCloud, for example). The size is always returned for file://
locations.{ exists: false, isDirectory: false }
. Else returns a Promise that resolves to an object with the following fields:true
.true
if this is a directory, false
if it is a fileCameraRoll.getPhotos()
, only present if the size
option was truthy.file://
URI pointing to the file. This is the same as the fileUri
input parameter.md5
option was truthy. Contains the MD5 hash of the file.data:image/png;base64,
to use it as Base64.file://
URI to the file or directory.FileSystem.EncodingType.UTF8
, FileSystem.EncodingType.Base64
. Default is FileSystem.EncodingType.UTF8
.encoding: FileSystem.EncodingType.Base64
and position
is defined.encoding: FileSystem.EncodingType.Base64
and length
is defined.file://
URI to the file or directory.FileSystem.EncodingType.UTF8
, FileSystem.EncodingType.Base64
. Default is FileSystem.EncodingType.UTF8
file://
URI to the file or directory.true
, don't throw an error if there is no file or directory at this URI. false
by default.file://
URI to the file or directory at its original location.file://
URI to the file or directory at what should be its new location.CameraRoll.getPhotos()
. See supported URI schemes.file://
URI to the new copy to create.file://
URI to the new directory to create.true
, create any non-existent parent directories when creating the directory at fileUri
. If false
, raises an error if any of the intermediate parent directories does not exist or if the child directory already exists. false
by default.file://
URI to the directory.fileUri
.FileSystem.downloadAsync( 'http://techslides.com/demos/sample-videos/small.mp4', FileSystem.documentDirectory + 'small.mp4' ) .then(({ uri }) => { console.log('Finished downloading to ', uri); }) .catch(error => { console.error(error); });
true
, include the MD5 hash of the file in the returned object. false
by default. Provided for convenience since it is common to check the integrity of a file immediately after downloading.FileSystemSessionType.BACKGROUND
.file://
URI pointing to the file. This is the same as the fileUri
input parameter.md5
option was truthy. Contains the MD5 hash of the file.fileUri
to the remote url.FileSystemSessionType.BACKGROUND
.FileSystemUploadType.BINARY_CONTENT
.uploadType
is equal FileSystemUploadType.MULTIPART
, more options are available:DownloadResumable
object which can start, pause, and resume a download of contents at a remote URI to a file in the app's file system. Please note: You need to call downloadAsync()
, on a DownloadResumable
instance to initiate the download. The DownloadResumable
object has a callback that provides download progress updates. Downloads can be resumed across app restarts by using AsyncStorage
to store the DownloadResumable.savable()
object for later retrieval. The savable
object contains the arguments required to initialize a new DownloadResumable
object to resume the download after an app restart. The directory for a local file uri must exist prior to calling this function.true
, include the MD5 hash of the file in the returned object. false
by default. Provided for convenience since it is common to check the integrity of a file immediately after downloading.-1
means that the server did not return the Content-Length
header and the total size is unknown. Without this header, you won't be able to track the download progress.Note: When the app has been moved to the background, this callback won't be fired until it's moved to the foreground.
DownloadResumable
object automatically when a download is paused. When initializing a new DownloadResumable
this should be null
.file://
URI pointing to the file. This is the same as the fileUri
input parameter.md5
option was truthy. Contains the MD5 hash of the file.resumeData
is added to the DownloadResumable
object after a successful pause operation. Returns an object that can be saved with AsyncStorage
for future retrieval (the same object that is returned from calling FileSystem.DownloadResumable.savable()
. Please see the example below.true
, include the MD5 hash of the file in the returned object. false
by default. Provided for convenience since it is common to check the integrity of a file immediately after downloading.file://
URI pointing to the file. This is the same as the fileUri
input parameter.md5
option was truthy. Contains the MD5 hash of the file.AsyncStorage
for future retrieval.true
, include the MD5 hash of the file in the returned object. false
by default. Provided for convenience since it is common to check the integrity of a file immediately after downloading.file://
URI and convert it into content URI (content://
) so that it can be access by other applications outside of Expo.FileSystem.getContentUriAsync(uri).then(cUri => { console.log(cUri); IntentLauncher.startActivityAsync('android.intent.action.VIEW', { data: cUri, flags: 1, }); });
content://
URI pointing to the file. The URI is the same as the fileUri
input parameter but in a different format.FileSystem.getFreeDiskStorageAsync().then(freeDiskStorage => { // Android: 17179869184 // iOS: 17179869184 });
MAX_SAFE_INTEGER
if the capacity is greater than 253 - 1 bytes.FileSystem.getTotalDiskCapacityAsync().then(totalDiskCapacity => { // Android: 17179869184 // iOS: 17179869184 });
MAX_SAFE_INTEGER
if the capacity is greater than 253 - 1 bytes.content://
, you cannot use FileSystem.readAsStringAsync()
, but you can use FileSystem.copyAsync()
which supports this scheme.Method name | Android | iOS |
---|---|---|
getInfoAsync | file:// ,content:// ,asset:// ,no scheme* | file:// ,ph:// ,assets-library:// |
readAsStringAsync | file:// ,asset:// | file:// |
writeAsStringAsync | file:// | file:// |
deleteAsync | file:// | file:// |
moveAsync | Source:file:// Destination: file:// | Source:file:// Destination: file:// |
copyAsync | Source:file:// ,content:// ,asset:// ,no scheme* Destination: file:// | Source:file:// ,ph:// ,assets-library:// Destination: file:// |
makeDirectoryAsync | file:// | file:// |
readDirectoryAsync | file:// | file:// |
downloadAsync | Source:http:// ,https:// Destination: file:// | Source:http:// ,https:// Destination: file:// |
uploadAsync | Source:file:// Destination: http:// https:// | Source:file:// Destination: http:// https:// |
createDownloadResumable | Source:http:// ,https:// Destination: file:// | Source:http:// ,https:// Destination: file:// |