-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms-full.txt
More file actions
1908 lines (1207 loc) · 84.5 KB
/
llms-full.txt
File metadata and controls
1908 lines (1207 loc) · 84.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# React Native document picker & viewer
> Document picker and viewer for React Native and Expo apps (Android, iOS). Packages: @react-native-documents/picker, @react-native-documents/viewer
## Overview
`@react-native-documents/picker` lets users pick, import, or save documents from the device's file system. `@react-native-documents/viewer` previews documents using native viewers (QuickLook on iOS, Intent.ACTION_VIEW on Android).
Key features:
- **Import mode**: pick a file and keep your own copy of it
- **Open mode**: access the selected document directly, with optional long-term access permissions that persist across app restarts
- **Save As dialog**: present `saveDocuments()` to let users save files to a location of their choice
- **Directory picker**: pick a directory for file I/O with optional long-term access
- **Virtual files**: handle Android virtual files (Google Docs, Sheets) via `allowVirtualFiles`
- **Document viewer**: preview files by uri or bookmark using `viewDocument()`
- **keepLocalCopy**: separate file picking from copying, making your app more responsive
Key patterns:
- Use `pick()` to present the document picker, destructure the result: `const [result] = await pick()`
- Handle errors with `isErrorWithCode()` helper and `errorCodes` object
- Use `keepLocalCopy()` after picking to save to app storage (replaces the old `copyTo` option)
- Use `requestLongTermAccess` for persistent file access across app restarts
## Installation
Depending on what module you need, install one or both of the packages:
```bash
yarn add @react-native-documents/picker
```
```bash
yarn add @react-native-documents/viewer
```
## Setting up
The packages are designed to support last 3 stable versions of RN. However, they very likely work with RN 0.76 and up.
### Expo
:::info
These packages cannot be used in ["Expo Go"](https://docs.expo.dev/workflow/overview/#expo-go-an-optional-tool-for-learning) because they include custom native code.
However, you can add custom native code to an Expo app through a [development build](https://docs.expo.dev/workflow/overview/#development-builds). That is the officially recommended approach for building Expo apps. See the commands below to do this.
:::
```bash
# install the package first
# Build the app locally
expo prebuild --clean
expo run:ios
expo run:android
```
### React Native
Install the package and then run `pod install` from the ios directory. Then rebuild your project with Xcode.
If you're using the [New Architecture](https://reactnative.dev/docs/new-architecture-intro), it's strongly recommended to use the latest stable release of RN.
---
## Introduction
Welcome to the docs for `@react-native-documents/picker` and `@react-native-documents/viewer` packages. These packages provide a way to pick, save ('save as' dialog) documents and view documents on the device's file system or remote locations.
Originally, there was only `react-native-document-picker` ([see here](https://github.com/react-native-documents/document-picker/tree/master)), but the package was fully rewritten and published in 1/2025 and the `viewer` package was added.
## What's new in the full rewrite?
There's the improved (list of changes below) picker package (called `@react-native-documents/picker`) with api that's very similar to the [original](https://github.com/react-native-documents/document-picker/tree/master). Secondly, there's the completely new `@react-native-documents/viewer` package which is designed to work well together with `picker`.
### TypeScript
- improved type definitions that make use of [Discriminated Unions](https://basarat.gitbook.io/typescript/type-system/discriminated-unions) and other goodies so that you don't try to read fields that are not there, and nullable fields are also reduced. (You can use vanilla JS too if you like.).
- [mocks](./jest-mocks.md) for testing
- `pickSingle` method was replaced for more streamlined `const [result] = pick()`
### iOS
- new: [`saveDocuments`](./picker/save-as-dialog) function
- new: [`isKnownType`](./picker/limiting-selectable-files.md#isknowntype) utility
- new: support for long-term file access permissions - across app and even device reboots! ([`requestLongTermAccess`](./picker/open-mode.mdx))
- new: [`keepLocalCopy`](./picker/keeping-local-copy.mdx) function that separates picking a file and copying it to a local directory. This makes your app more responsive: previously you'd use the `copyTo` option and before the resulting `Promise` resolved, you needed to wait not only for user to pick the file, but also for the file to be copied to your app's directory. For large files or with slow network, this could be a problem that you, as a dev don't see, but your users do.
- improved: the majority of the code is now written in Swift, making code safer and more readable.
- improved: less use of the main thread.
- improved: using the new `UIDocumentPickerViewController` apis instead of those deprecated in iOS 14
- improved: instead of the old `copyTo` parameter making unnecessary copies, the new `keepLocalCopy` function moves the imported file.
### Android
- new: [`saveDocuments`](./picker/save-as-dialog) function
- new: support for [open mode](./picker/open-mode.mdx)
- new: support for long-term file access permissions - across app and even device reboots! ([`requestLongTermAccess`](./picker/open-mode.mdx))
- new: [`keepLocalCopy`](./picker/keeping-local-copy.mdx) function that separates picking a file and copying it to a local directory. This makes your app more responsive: previously you'd use the `copyTo` option and before the resulting `Promise` resolved, you needed to wait not only for user to pick the file, but also for the file to be copied to your app's directory. For large files or with slow network, this could be a problem that you, as a dev don't see, but your users do.
- new: support for [virtual files](./picker/virtual-files.md)
- improved: deprecated [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask) usage was replaced with Kotlin Coroutines.
- improved: the code is better at operating with I/O, for example buffering is replaced with a potentially much more efficient alternative from `java.nio`
- improved: reading file metadata is more defensive and efficient because only the necessary columns are queried from [ContentResolver](<https://developer.android.com/reference/android/content/ContentResolver#query(android.net.Uri,%20java.lang.String[],%20android.os.Bundle,%20android.os.CancellationSignal)>). The native Android apis are full of calls that can return null or throw so extra care is taken to handle these cases.
### Windows
Windows is not supported at the moment but you can try your luck [here](https://github.com/ClaudiuHBann/document-picker-windows). While there was Windows-related code in the public module, it was not maintained and probably does not work.
### How do I know it works?
With so many changes, you might wonder if the new package is stable - especially with Android because... well, we know Android 😜.
To prove the new code is solid, I have written an e2e test suite using Appium that covers the majority of the features:
- import mode
- open mode
- viewing files, including long-term permissions
<iframe width="560" height="315" src="https://www.youtube.com/embed/tE3WMA4nxGE?si=N8p535owAFnenBwz" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
The test suite focuses on Android, and was executed on real devices from Samsung, Google and Huawei, with Android versions ranging between 8 and 14. iOS tests were done manually on a real device with iOS 17.
As a result, I have greater confidence in the new package than in the old one!
## Say thanks
I ([vonovak](https://github.com/vonovak)) have been maintaining the original [`react-native-document-picker`](https://github.com/react-native-documents/document-picker/tree/master) package more or less since 2020. The package has been used by thousands of devs, but I could see that there was a lot to improve.
I decided to rewrite the package from scratch and make it better! The new package has a new name: `@react-native-documents/picker`.
While I was at it, I also created a new `viewer` package.
If you want to say thanks, go to my [GitHub Sponsors profile](https://github.com/sponsors/vonovak).
## Migrating from the old package
See the 3-step [migration guide](./migration.md).
---
## Import mode
<details>
<summary>Video introduction</summary>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/CUNDpURFx4U?si=Qw1xpG4d4aNwJgdS&start=65"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
</details>
Use import mode when you want to pick a file (from the device, cloud storage, etc.) and keep your own copy of it. That means if the original file changes, the copy you have will not change.
If you instead want to keep a reference to the original picked file, use the [open mode](./open-mode.mdx).
Import mode is the default way to use the module, as in the example below.
```tsx title="picking a file in import mode"
import { pick } from '@react-native-documents/picker'
return (
<Button
title="single file import"
onPress={async () => {
try {
const [pickResult] = await pick()
// const [pickResult] = await pick({mode:'import'}) // equivalent
// do something with the picked file
} catch (err: unknown) {
// see error handling
}
}}
/>
)
```
:::tip
`pick()`, when it resolves, always returns at least one picked document, and TypeScript won't complain about `pickedFile` being `undefined` due to the array destructuring, even with `noUncheckedIndexedAccess: true` in your `tsconfig.json`.
:::
### Next steps
After importing a file, it's likely that you'll want to work with a local copy of it: see [keeping a local copy](./keeping-local-copy.mdx). This is because on Android, the picked files may point to resources that are not present on the device but in some cloud location. On iOS, the picked files are always downloaded by the system, but they are stored as temporary files that are only available for a short time.
### How it works
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
<Tabs queryString="current-os" className="unique-tabs">
<TabItem value="android" label="Android">
Import mode uses [`Intent.ACTION_GET_CONTENT`](https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT) internally.
Read more about the difference between the two modes in [Android integration guide](./integrating-on-android.mdx).
With `ACTION_GET_CONTENT`, the returned uris are file references transient to your activity's current lifecycle. Regardless of the intent type, it is recommended you import a copy that you can read later, using [`keepLocalCopy`](./keeping-local-copy.mdx).
</TabItem>
<TabItem value="ios" label="iOS">
Import mode uses [UIDocumentPickerViewController init(forOpeningContentTypes:asCopy:)](https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller/3566733-init) internally.
In import mode, the picker gives you access to a local copy of the documents. The picked documents are temporary files and remain available only for a short time. Officially it's [until the application terminates](https://developer.apple.com/documentation/uikit/uidocumentpickerdelegate/2902364-documentpicker#discussion) but practically, it appears to be much shorter.
If you want to access a file longer, you have to use [`keepLocalCopy`](./keeping-local-copy.mdx), or the [open mode](./open-mode.mdx) instead.
</TabItem>
</Tabs>
### Import Options
| Name | Type | Description |
| :--------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type?` | `string` \| [`PredefinedFileTypes`](/docs/doc-picker-api#predefinedfiletypes) \| ([`PredefinedFileTypes`](/docs/doc-picker-api#predefinedfiletypes) \| `string`)[] | specify file type(s) that you want to pick. Use `types` for some predefined values. |
| `allowMultiSelection?` | `boolean` | Whether to allow multiple files to be picked |
| `allowVirtualFiles?` | `boolean` | Android only - Whether to allow [virtual files](./virtual-files.md) (such as Google docs or sheets) to be picked. False by default. |
| `presentationStyle?` | [`PresentationStyle`](/docs/doc-picker-api#presentationstyle) | iOS only - Controls how the picker is presented, e.g. on an iPad you may want to present it fullscreen. Defaults to `pageSheet`. |
| `transitionStyle?` | [`TransitionStyle`](/docs/doc-picker-api#transitionstyle) | iOS only - Configures the transition style of the picker. Defaults to coverVertical, when the picker is presented, its view slides up from the bottom of the screen. |
### Import result
The result of the `pick` function is an array of picked files (the result is the same for both `open` and `import` modes). The array has a length of 1 if `allowMultiSelection` is `false` (the default), and 1 or more if `allowMultiSelection` is `true`.
import OptionalFieldsNote from './_optionalFieldsNote.mdx'
<OptionalFieldsNote />
Each picked file is represented by an object with the following properties:
| Name | Type | Description |
| :----------------------- | :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uri` | `string` | The URI of the picked file. Note that it is encoded, so you might need to [decode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) it for further processing. |
| `name` | `string` \| `null` | The name of the picked file, including the extension. It's very unlikely that it'd be `null` but in theory, it can happen. |
| `size` | `number` \| `null` | The size of the picked file in bytes. |
| `type` | `string` \| `null` | The MIME type of the picked file. |
| `hasRequestedType` | `boolean` | Android: Some [Document Providers](https://developer.android.com/guide/topics/providers/content-provider-basics) on Android (especially those popular in Asia, it seems) do not respect the request for [limiting selectable file types](./limiting-selectable-files.md). `hasRequestedType` will be false if the user picked a file that does not match one of the requested types. You need to do your own post-processing and display an error to the user if this is important to your app. Always `true` on iOS. |
| `error` | `string` \| `null` | Error in case the file metadata could not be obtained. |
| `isVirtual` | `boolean` \| `null` | Android: Whether the file is a virtual file (such as Google docs or sheets). Will be `null` on pre-Android 7.0 devices. On iOS, it's always `false`. |
| `convertibleToMimeTypes` | `string`[] \| `null` | Android: The target types to which a virtual file can be converted. Useful for `keepLocalCopy`. This field is only specified if `isVirtual` is true, and only on Android 7.0+. Always `null` on iOS. |
| `nativeType` | `string` \| `null` | The "native" type of the picked file: on Android, this is the MIME type. On iOS, it is the UTType identifier. |
---
## Open mode
<details>
<summary>Video introduction</summary>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/CUNDpURFx4U?si=xr3jHKpWRDo3uFLi&start=219"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
</details>
In open mode, the returned uris refer directly to the selected documents.
This is particularly useful when you want to read an existing file without making a copy into your app or when you want to open and edit a file in-place (using the [`Viewer module`](../viewer)).
With `requestLongTermAccess`, your app is granted long-term read access to the file, also possibly with write access (to be clarified in a later docs update).
```tsx title="Picking a file in open mode"
import { pick } from '@react-native-documents/picker'
return (
<Button
title="open file"
onPress={async () => {
try {
const [result] = await pick({
mode: 'open',
})
console.log(result)
} catch (err) {
// see error handling
}
}}
/>
)
```
### How it works
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
<Tabs queryString="current-os" className="unique-tabs">
<TabItem value="android" label="Android">
Open mode uses [`Intent.ACTION_OPEN_DOCUMENT`](https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT) internally.
</TabItem>
<TabItem value="ios" label="iOS">
Open mode uses [UIDocumentPickerViewController init(forOpeningContentTypes:asCopy:)](https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller/3566733-init) internally.
</TabItem>
</Tabs>
### Open Options
| Name | Type | Description |
| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| `mode` | `'open'` | specify that you want the picker to function in the "open" mode. |
| `type?` | `string` \| [`PredefinedFileTypes`](/docs/doc-picker-api#predefinedfiletypes) \| ([`PredefinedFileTypes`](/docs/doc-picker-api#predefinedfiletypes) \| `string`)[] | specify file type(s) that you want to pick. Use `types` for some predefined values. |
| `requestLongTermAccess?` | `boolean` | Whether to ask for long-term access permissions. False by default. |
| `allowMultiSelection?` | `boolean` | Whether to allow multiple files to be picked. False by default. |
| `allowVirtualFiles?` | `boolean` | Android only - Whether to allow [virtual files](./virtual-files.md) (such as Google docs or sheets) to be picked. False by default. |
| `presentationStyle?` | [`PresentationStyle`](/docs/doc-picker-api#presentationstyle) | iOS only - Controls how the picker is presented, e.g. on an iPad you may want to present it fullscreen. Defaults to `pageSheet`. |
| `transitionStyle?` | [`TransitionStyle`](/docs/doc-picker-api#transitionstyle) |
### Open result
The shape of result is the same for both `open` and `import` modes.
import OptionalFieldsNote from './_optionalFieldsNote.mdx'
<OptionalFieldsNote />
Each picked file is represented by an object with the following properties:
| Name | Type | Description |
| :----------------------- | :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uri` | `string` | The URI of the picked file. Note that it is encoded, so you might need to [decode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) it for further processing. |
| `name` | `string` \| `null` | The name of the picked file, including the extension. It's very unlikely that it'd be `null` but in theory, it can happen. |
| `size` | `number` \| `null` | The size of the picked file in bytes. |
| `type` | `string` \| `null` | The MIME type of the picked file. |
| `hasRequestedType` | `boolean` | Android: Some [Document Providers](https://developer.android.com/guide/topics/providers/content-provider-basics) on Android (especially those popular in Asia, it seems) do not respect the request for [limiting selectable file types](./limiting-selectable-files.md). `hasRequestedType` will be false if the user picked a file that does not match one of the requested types. You need to do your own post-processing and display an error to the user if this is important to your app. Always `true` on iOS. |
| `error` | `string` \| `null` | Error in case the file metadata could not be obtained. |
| `isVirtual` | `boolean` \| `null` | Android: Whether the file is a virtual file (such as Google docs or sheets). Will be `null` on pre-Android 7.0 devices. On iOS, it's always `false`. |
| `convertibleToMimeTypes` | `string`[] \| `null` | Android: The target types to which a virtual file can be converted. Useful for `keepLocalCopy`. This field is only specified if `isVirtual` is true, and only on Android 7.0+. Always `null` on iOS. |
| `nativeType` | `string` \| `null` | The "native" type of the picked file: on Android, this is the MIME type. On iOS, it is the UTType identifier. |
## Long-term file access
When `requestLongTermAccess` is set to `true`, your app will be able to access the file even after the app or device is restarted.
If you've requested long-term access to a directory or file, the response object will contain [BookmarkingResponse](/docs/doc-picker-api#bookmarkingresponse).
In order to access the same directory or file in the future, you must check `bookmarkStatus` and store the `bookmark` opaque string.
:::note Advanced
When you want to access the file later (for example in your own native module), you can use the `bookmark` to resolve the file uri. See the Document viewer source on how to do it, if you need this.
:::
```tsx title="Request long-term access to a file"
import { pick, types } from '@react-native-documents/picker'
return (
<Button
title="open pdf file with requestLongTermAccess: true"
onPress={async () => {
try {
const [result] = await pick({
mode: 'open',
requestLongTermAccess: true,
type: [types.pdf],
})
if (result.bookmarkStatus === 'success') {
const bookmarkToStore = {
fileName: result.name ?? 'unknown name',
bookmark: result.bookmark,
}
localStorage.set('bookmark', JSON.stringify(bookmarkToStore))
} else {
console.error(result)
}
} catch (err) {
// see error handling
}
}}
/>
)
```
### Releasing Long Term Access
This is an Android-only feature. When you no longer need access to the file or location, you should release the long-term access by calling `releaseLongTermAccess`. Calling this on iOS will resolve.
See [Android documentation](<https://developer.android.com/reference/android/content/ContentResolver#releasePersistableUriPermission(android.net.Uri,%20int)>) for more information.
### Releasing (stopping) Secure Access
This is an iOS-only feature. When you no longer need access to the file or location, you should release the secure access by calling `releaseSecureAccess`. Calling this on Android will resolve.
See [iOS documentation](https://developer.apple.com/documentation/foundation/nsurl/1413736-stopaccessingsecurityscopedresou) for more information.
---
## 'Save As' dialog
[`saveDocuments`](/docs/doc-picker-api#savedocuments) presents the user with a dialog to save the provided file(s) to a location of their choice.
<details>
<summary>UI screenshots</summary>
| Android | iOS |
| :--------------------------------------------------------------: | :----------------------------------------------------------: |
| | |
</details>
This is useful if you want to export some user-generated content (or for example a log file you created during development) from within your app to a user-selected location.
On Android, only one file can be saved at a time but on iOS, multiple files can be saved at once. Read more about the [parameters](/docs/doc-picker-api#savedocumentsoptions) of the function.
### How it works
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
<Tabs queryString="current-os" className="unique-tabs">
<TabItem value="android" label="Android">
Uses [`Intent.ACTION_CREATE_DOCUMENT`](https://developer.android.com/reference/android/content/Intent#ACTION_CREATE_DOCUMENT) internally.
This is a two-step process: first, the user provides the target (location and name), then the package copies the source to the selected target.
</TabItem>
<TabItem value="ios" label="iOS">
Uses [UIDocumentPickerViewController init(forExporting:)](https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller/3566730-init) internally.
Note that unlike on Android, your app does not posses any permissions to the target file.
</TabItem>
</Tabs>
---
```tsx title="Example: opening a 'Save As' dialog"
import { saveDocuments } from '@react-native-documents/picker'
return (
<Button
title="Save some text file to a user-defined location"
onPress={async () => {
const [{ uri: targetUri }] = await saveDocuments({
sourceUris: ['some file uri'],
copy: false,
mimeType: 'text/plain',
fileName: 'some file name',
})
}}
/>
)
```
---
## Keeping a local copy of the picked files {#keepLocalCopy}
[`keepLocalCopy`](/docs/doc-picker-api#keeplocalcopy) makes the file available in the app's storage. The behavior is different on iOS and Android:
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
<Tabs queryString="current-os" className="unique-tabs">
<TabItem value="android" label="Android">
This method opens an `InputStream` pointing to the picked `content://` uri (from both Open and Import modes) and stores its bytes into a file - i.e. it can be used to "convert" a `content://` Uri into a local file. This file's location is determined by the `destination` parameter.
It also "converts" [virtual files](./virtual-files.md) (such as Google Docs or sheets) into local files.
</TabItem>
<TabItem value="ios" label="iOS">
On iOS, `keepLocalCopy` is only supported for the Import mode at the moment.
Calling this method is strongly recommended, though not strictly necessary, as the file is already temporarily available in a location in the app's sandbox when it is picked.
However, iOS appears to delete the file rather soon after it is returned to your app, hence the recommendation.
`keepLocalCopy` is useful if you need to prevent / delay the file being deleted by the system (by moving it to the app's Documents / Cache directory, respectively).
To prevent deletion, call `keepLocalCopy()` and pass `destination: "documentDirectory"`.
This moves the file from the temporary location it is in when it is picked, into Documents directory, where the file lives until the app is uninstalled.
</TabItem>
</Tabs>
---
:::note
For each call of `keepLocalCopy`, a new unique directory is created in the app's storage, and the files are placed into it.
This way, the files are isolated and subsequent calls to `keepLocalCopy` with the same file names do not overwrite the previous files.
When writing to the filesystem, [path traversal vulnerability](https://owasp.org/www-community/attacks/Path_Traversal) is prevented. Writing files outside the intended destination will error.
:::
```tsx title="Example: keeping a local copy of the picked file"
import { pick, keepLocalCopy } from '@react-native-documents/picker'
return (
<Button
title="single file import, and ensure it is available in the local storage"
onPress={async () => {
try {
const [{ name, uri }] = await pick()
const [copyResult] = await keepLocalCopy({
files: [
{
uri,
fileName: name ?? 'fallback-name',
},
],
destination: 'documentDirectory',
})
if (copyResult.status === 'success') {
// do something with the local copy:
console.log(copyResult.localUri)
}
} catch (err) {
// see error handling
}
}}
/>
)
```
---
## Limiting selectable file types
<details>
<summary>Video introduction</summary>
<iframe width="560" height="315" src="https://www.youtube.com/embed/CUNDpURFx4U?si=xr3jHKpWRDo3uFLi&start=150" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</details>
The default document picker allows any file to be selected (except [virtual files](./virtual-files.md)). Use the `type` parameter of `pick()` to restrict the selectable file types.
- On iOS, these are Apple [Uniform Type Identifiers](https://developer.apple.com/documentation/uniformtypeidentifiers/system-declared_uniform_type_identifiers) such as `public.plain-text`.
- On Android, these are MIME types such as `text/plain` or partial MIME types such as `image/*`. See [common MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types) or a more comprehensive [IANA Media Types listing](https://www.iana.org/assignments/media-types/media-types.xhtml).
Figuring out the correct MIME type or UTType identifier for a file type can be a bit of a hassle. To make it easier, the module exports the [`isKnownType`](#isknowntype) utility and several [predefined file types](#predefined-file-types) that you can use.
:::warning
On Android, some [Document Providers](https://developer.android.com/guide/topics/providers/content-provider-basics) (this seems to be a problem especially in Asia) ignore the `type` parameter and allow any file to be selected. This is a problem with the Document Provider, not this module.
To detect this case, check the [`hasRequestedType`](../../doc-picker-api#documentpickerresponse) field and handle the situation in your app.
:::
```tsx title="Limiting selectable file types to pdf and docx"
import { pick, types } from '@react-native-documents/picker'
return (
<Button
title="import multiple docx or pdf files"
onPress={() => {
pick({
allowMultiSelection: true,
// highlight-next-line
type: [types.pdf, types.docx],
})
.then((res) => {
const allFilesArePdfOrDocx = res.every((file) => file.hasRequestedType)
if (!allFilesArePdfOrDocx) {
// tell the user they selected a file that is not a pdf or docx
}
addResult(res)
})
.catch(handleError)
}}
/>
)
```
### isKnownType
`isKnownType` is a handy utility function that given one of:
- UTType identifier string
- MIME type string
- File extension string
returns the corresponding MIME type, file extension, and UTType identifier.
```ts
import { isKnownType } from '@react-native-documents/picker'
const { isKnown, mimeType, preferredFilenameExtension } = isKnownType({
kind: 'extension',
value: 'pdf',
})
```
If you know the file extension (or the MIME, or the UTType), then use `isKnownType` to find the corresponding MIME type for Android or UTType for iOS. Then pass the result to the `type` parameter of `pick`.
:::note
Prefer using the iOS implementation of `isKnownType`. On Android, the function does not provide `UTType` identifier information (as it's an iOS-only concept) and the results may not be as accurate.
Different devices, based on the installed apps, may recognize different file types.
:::
### Predefined File Types
These are the most common file types, and are available in the `types` export. See the usage example above.
```ts
import { types } from '@react-native-documents/picker'
```
- `types.allFiles`: All document types, on Android this is `*/*`, on iOS it's `public.item`
- `types.images`: All image types
- `types.plainText`: Plain text files
- `types.audio`: All audio types
- `types.video`: All video types
- `types.pdf`
- `types.zip`
- `types.csv`
- `types.json`
- `types.doc`
- `types.docx`
- `types.ppt`
- `types.pptx`
- `types.xls`
- `types.xlsx`
---
## Directory picker
This module allows you to pick a directory from the file system. The chosen directory can then be used for file I/O operations.
When `requestLongTermAccess` is set to `true`, your app will be able to access the directory even after the app is restarted.
If you've requested long-term access to a directory or file, the response object will contain [BookmarkingResponse](/docs/doc-picker-api#bookmarkingresponse).
Please note there are some [security limitations](https://developer.android.com/training/data-storage/shared/documents-files#document-tree-access-restrictions).
```tsx title="Selecting a directory"
import { pickDirectory } from '@react-native-documents/picker'
return (
<Button
title="open directory"
onPress={async () => {
try {
const { uri } = await pickDirectory({
requestLongTermAccess: false,
})
// do something with the uri
} catch (err) {
// see error handling section
console.error(err)
}
}}
/>
)
```
### How it works
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
<Tabs queryString="current-os" className="unique-tabs">
<TabItem value="android" label="Android">
Open mode uses [`Intent.ACTION_OPEN_DOCUMENT_TREE`](https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT_TREE) internally.
</TabItem>
<TabItem value="ios" label="iOS">
Open mode uses [UIDocumentPickerViewController init(forOpeningContentTypes:asCopy:)](https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller/3566733-init) internally.
</TabItem>
</Tabs>
### Writing to the directory location
In order to write to the user-selected location, this approach needs to be used:
- on Android: https://stackoverflow.com/a/61120265
- on iOS: [docs](https://developer.apple.com/documentation/foundation/nsfilemanager/1410695-createfileatpath)
### Releasing Long Term Access
This is an Android-only feature. When you no longer need access to the file or location, you should release the long-term access by calling `releaseLongTermAccess`. Calling this on iOS will resolve.
See [Android documentation](<https://developer.android.com/reference/android/content/ContentResolver#releasePersistableUriPermission(android.net.Uri,%20int)>) for more information.
### Releasing (stopping) Secure Access
This is an iOS-only feature. When you no longer need access to the file or location, you should release the secure access by calling `releaseSecureAccess`. Calling this on Android will resolve.
See [iOS documentation](https://developer.apple.com/documentation/foundation/nsurl/1413736-stopaccessingsecurityscopedresou) for more information.
---
## Virtual files
Virtual files are an Android-only concept. You have almost surely encountered them in your Google Drive - all the Google Docs, Sheets, Presentations, etc. are virtual files and cannot normally be selected.
Pass `allowVirtualFiles: true` to the `pick` function to allow picking virtual files in import mode.
When a virtual file is picked, the `isVirtual` field is `true`, and the `convertibleToMimeTypes` field contains an array of [`VirtualFileMeta`](/docs/doc-picker-api#virtualfilemeta).
This array describes what kind(s) of regular file the virtual file can be exported into - for example, Google Docs files can be exported as `application/pdf` and so the array will be `[{ mimeType: 'application/pdf', extension: 'pdf' }]`.
:::note
Picking virtual files is supported since Android 7.0.
:::
## Obtaining a regular file from a virtual file
If you want to export a virtual file into a local one, use the [`keepLocalCopy`](./keeping-local-copy.mdx) function and
1. double-check that the `fileName` parameter includes the extension.
2. pass a `mimeType` value to the `convertVirtualFileToType` parameter.
```tsx title="Picking a virtual file and exporting it to a local one"
<Button
title="import virtual file (such as a document from GDrive)"
onPress={async () => {
const [file] = await pick({
allowVirtualFiles: true,
})
const { name, uri: pickedUri, convertibleToMimeTypes } = file
const virtualFileMeta = convertibleToMimeTypes && convertibleToMimeTypes[0]
invariant(name && virtualFileMeta, 'name and virtualFileMeta is required')
const [copyResult] = await keepLocalCopy({
files: [
{
uri: pickedUri,
fileName: `${name}.${virtualFileMeta.extension ?? ''}`,
convertVirtualFileToType: virtualFileMeta.mimeType,
},
],
destination: 'cachesDirectory',
})
if (copyResult.status === 'success') {
const localCopy = copyResult.localUri
// do something with the local copy
}
}}
/>
```
For viewing or editing of virtual files you'll need to rely on the app that provided the virtual file (for example, Google Docs app for Google Docs files). The [Document Viewer](../viewer.mdx) module can help you with that.
Learn more about virtual files in [this video](https://www.youtube.com/watch?v=4h7yCZt231Y).
---
## Android usage notes
:::tip
The TL;DR version is: the Open and Import modes on Android aren't too different in practice, and you can usually use either one, often combined with [`keepLocalCopy`](./keeping-local-copy.mdx).
:::
### Screenshots
Sometimes pictures are worth a thousand words. Here are some example screenshots of the Open and Import modes on Android.
Notice that in the "Import Mode (unrestricted file types)" case, the list is taller than the screen.
import Image from '@theme/IdealImage'
| Open Mode (unrestricted file types) | Import Mode (unrestricted file types) |
| :---------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------: |
| <Image img={require('/img/modes/open-unrestricted.jpg')} style={{maxWidth: 400}} /> | <Image img={require('/img/modes/import-unrestricted.jpg')} style={{maxWidth: 400}} /> |
| Open Mode (restricted to picking pdf) | Import Mode (restricted to picking pdf) |
| :------------------------------------------------------------------------: | :--------------------------------------------------------------------------: |
| <Image img={require('/img/modes/open-pdf.jpg')} style={{maxWidth: 400}} /> | <Image img={require('/img/modes/import-pdf.jpg')} style={{maxWidth: 400}} /> |
### Resources
Assorted links to relevant resources:
- [`Intent.ACTION_GET_CONTENT` (used in Import mode)](https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT)
- [`Intent.ACTION_OPEN_DOCUMENT` (used in Open mode)](https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT)
- [Open a specific type of file](https://developer.android.com/guide/components/intents-common#OpenFile)
- [What is the real difference between ACTION_GET_CONTENT and ACTION_OPEN_DOCUMENT?](https://stackoverflow.com/questions/36182134/what-is-the-real-difference-between-action-get-content-and-action-open-document)
- [note in "Write a client app"](https://developer.android.com/guide/topics/providers/document-provider.html#client)
---
## Document Viewer
The viewer module is designed to work with the files that the document picker module returns. It supports both `uri` and `bookmark` coming from `open` and `import` modes, also supports virtual files and long-term access to the files.
The call to `viewDocument` returns a promise that resolves with `null` in case of success or rejects with an error. It is a "fire-and-forget" function, meaning that the promise resolves right after the package asks the OS to present the preview.
### How it works
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
<Tabs queryString="current-os" className="unique-tabs">
<TabItem value="android" label="Android">
`viewDocument` uses [`Intent.ACTION_VIEW`](https://developer.android.com/reference/android/content/Intent#ACTION_VIEW) internally.
</TabItem>
<TabItem value="ios" label="iOS">
`viewDocument` uses the [QuickLook framework](https://developer.apple.com/documentation/quicklook) internally.
</TabItem>
</Tabs>
### View a document given a `uri`
Uri would come from the [open](./picker/open-mode.mdx) or [import](./picker/import-mode.mdx) modes of the document picker.
> See more in the [API reference](../doc-viewer-api#optionsviewuri)
```tsx title="Previewing a document given a uri"
import { viewDocument } from '@react-native-documents/viewer'
return (
<Button
title="view the last imported file"
onPress={() => {
const uriToOpen = 'file:///path/to/your/file'
viewDocument({ uri: uriToOpen, mimeType: 'some-mime' }).catch(handleError)
}}
/>
)
```
### View a document given a `bookmark`
`bookmark` would come from the [open](./picker/open-mode.mdx) mode, with the `requestLongTermAccess` option set to `true`.
> See more in the [API reference](../doc-viewer-api#optionsviewbookmark)
```tsx title="Previewing a document given a bookmark"
import { viewDocument } from '@react-native-documents/viewer'
return (
<Button
title="view the last imported file"
onPress={() => {
const bookmark = '...'
viewDocument({ bookmark }).catch(handleError)
}}
/>
)
```
---
## Error handling
This page describes the case when calling any of the modules' method rejects. Keep in mind other errors can also happen in `pick` ([see `error` and `hasRequestedType`](../doc-picker-api#documentpickerresponse)) and `keepLocalCopy` ([see `copyError`](../doc-picker-api#localcopyresponse)).
### Error codes
Both `picker` and `viewer` expose the `errorCodes` object which contains an object of possible error codes that can be returned by the native module.
Error codes are useful when determining which kind of error has occurred during the picking or viewing process.
| Error Code Key | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `IN_PROGRESS` | This is rather a warning, that happens when you invoke an operation (e.g. `pick`) while a previous one has not finished yet. For example: if you call `pick()` quickly twice in a row, 2 calls to `pick()` in the native module will be done. The first call will open the native document picker and user action will be expected. The promise from the second call to `pick` will be rejected with this error. Later, the first promise will resolve (or reject) with the actual files that the user has selected. Only one document picker window will be presented to the user. The reason the module explicitly rejects "duplicated" calls is to avoid memory leaks and to inform you that something probably isn't done right. |
| `UNABLE_TO_OPEN_FILE_TYPE` | When you try to use the picker or viewer using a configuration that system cannot comply with. On Android, this corresponds to [ActivityNotFoundException](https://developer.android.com/reference/android/content/ActivityNotFoundException). On iOS, this only happens in the Viewer module when you attempt to preview a file that's not supported by the [QuickLook framework](https://developer.apple.com/documentation/quicklook/qlpreviewcontroller/1617016-canpreviewitem?language=objc). |
| `OPERATION_CANCELED` | When user cancels the operation |
:::note
In a future release, `OPERATION_CANCELED` will be replaced with a more streamlined cancellation handling. I'm keeping it now to make [migration](migration.md) easier.
:::
```ts title="error-handling.ts"
import { errorCodes } from '@react-native-documents/picker'
// or
import { errorCodes } from '@react-native-documents/viewer'
const handleError = (err: unknown) => {
if (isErrorWithCode(err)) {
switch (err.code) {
case errorCodes.IN_PROGRESS:
console.warn('user attempted to present a picker, but a previous one was already presented')
break
case errorCodes.UNABLE_TO_OPEN_FILE_TYPE:
setError('unable to open file type')
break
case errorCodes.OPERATION_CANCELED:
// ignore
break
default:
setError(String(err))
console.error(err)
}
} else {
setError(String(err))
}
}
```
### `isErrorWithCode(value)`
TypeScript helper to check if the passed parameter is an instance of `Error` which has the `code` property. All errors thrown by the picker and viewer native modules have the `code` property, which contains a value from [`errorCodes`](#error-codes) or some other string for the less-usual errors.
`isErrorWithCode` can be used to avoid `as` casting when you want to access the `code` property on errors returned by the module.
```ts
import { pick, isErrorWithCode } from '@react-native-documents/picker'
try {
const [pickResult] = await pick()
// do something with pickResult
} catch (error) {
if (isErrorWithCode(error)) {
// here you can safely read `error.code` and TypeScript will know that it has a value
} else {
// this error does not have a `code`, and does not come from the native module
}
}
```
---
## Jest module mocks
You will need to mock the functionality of the native modules once you require them from your test files - otherwise you'll get [this error](https://github.com/rnmods/react-native-document-picker/issues/702).
The packages provide Jest mocks that you can add to the [`setupFiles`](https://jestjs.io/docs/configuration#setupfiles-array) array in the Jest config.
By default, the mocks behave as if the calls were successful and return mock document data.
```json title="jest.config"
{
"setupFiles": [
"./node_modules/@react-native-documents/picker/jest/build/jest/setup.js",
"./node_modules/@react-native-documents/viewer/jest/build/jest/setup.js"
]
}
```
---
## Migrating from the old document-picker
The new package has a new name (`@react-native-documents/picker`), so you need to update your import statements.
### Migrating your code
Good news: You need to make only a few changes:
1. update import statements
```ts
import { ... } from 'react-native-document-picker'
```
becomes
```ts
import { ... } from '@react-native-documents/picker'
```
Also, if you previously used a default import like this:
```ts
import DocumentPicker from 'react-native-document-picker'
```
you should update it to use named imports for the methods you need (such as `pick`, `keepLocalCopy`, etc):
```ts
import { pick, keepLocalCopy } from '@react-native-documents/picker'
```
2. remove `pickSingle`
Replace `pickSingle` with `pick`:
```ts
const result = await pickSingle(options)
```
becomes:
```ts