Limiting selectable file types
Video introduction
The default document picker allows any file to be selected (except virtual files). Use the type
parameter of pick()
to restrict the selectable file types.
-
On iOS, these are Apple Uniform Type Identifiers such as
public.plain-text
. -
On Android, these are MIME types such as
text/plain
or partial MIME types such asimage/*
. See common MIME types or a more comprehensive IANA Media Types listing.
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
utility and several predefined file types that you can use.
On Android, some Document Providers (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
field and handle the situation in your app.
import { pick, types } from '@react-native-documents/picker'
return (
<Button
title="import multiple docx or pdf files"
onPress={() => {
pick({
allowMultiSelection: true,
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.
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
.
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.
import { types } from '@react-native-documents/picker'
types.allFiles
: All document types, on Android this is*/*
, on iOS it'spublic.item
types.images
: All image typestypes.plainText
: Plain text filestypes.audio
: All audio typestypes.video
: All video typestypes.pdf
types.zip
types.csv
types.json
types.doc
types.docx
types.ppt
types.pptx
types.xls
types.xlsx