Security News
The Dark Side of Open Source
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
use-file-picker
Advanced tools
Readme
🏠 Homepage
npm i use-file-picker
or
yarn add use-file-picker
import { useFilePicker } from 'use-file-picker';
import React from 'react';
export default function App() {
const { openFilePicker, filesContent, loading } = useFilePicker({
accept: '.txt',
});
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={() => openFileSelector()}>Select files</button>
<br />
{filesContent.map((file, index) => (
<div>
<h2>{file.name}</h2>
<div key={index}>{file.content}</div>
<br />
</div>
))}
</div>
);
}
import { useFilePicker } from 'use-file-picker';
import {
FileAmountLimitValidator,
FileTypeValidator,
FileSizeValidator,
ImageDimensionsValidator,
} from 'use-file-picker/validators';
export default function App() {
const { openFilePicker, filesContent, loading, errors } = useFilePicker({
readAs: 'DataURL',
accept: 'image/*',
multiple: true,
validators: [
new FileAmountLimitValidator({ max: 1 }),
new FileTypeValidator(['jpg', 'png']),
new FileSizeValidator({ maxFileSize: 50 * 1024 * 1024 /* 50 MB */ }),
new ImageDimensionsValidator({
maxHeight: 900, // in pixels
maxWidth: 1600,
minHeight: 600,
minWidth: 768,
}),
],
});
if (loading) {
return <div>Loading...</div>;
}
if (errors.length) {
return <div>Error...</div>;
}
return (
<div>
<button onClick={() => openFilePicker()}>Select files </button>
<br />
{filesContent.map((file, index) => (
<div key={index}>
<h2>{file.name}</h2>
<img alt={file.name} src={file.content}></img>
<br />
</div>
))}
</div>
);
}
import { useFilePicker } from 'use-file-picker';
export default function App() {
const { openFilePicker, filesContent, loading, errors } = useFilePicker({
readAs: 'DataURL',
accept: 'image/*',
multiple: true,
onFilesSelected: ({ plainFiles, filesContent, errors }) => {
// this callback is always called, even if there are errors
console.log('onFilesSelected', plainFiles, filesContent, errors);
},
onFilesRejected: ({ errors }) => {
// this callback is called when there were validation errors
console.log('onFilesRejected', errors);
},
onFilesSuccessfullySelected: ({ plainFiles, filesContent }) => {
// this callback is called when there were no validation errors
console.log('onFilesSuccessfullySelected', plainFiles, filesContent);
},
});
if (loading) {
return <div>Loading...</div>;
}
if (errors.length) {
return <div>Error...</div>;
}
return (
<div>
<button onClick={() => openFilePicker()}>Select files </button>
<br />
{filesContent.map((file, index) => (
<div key={index}>
<h2>{file.name}</h2>
<img alt={file.name} src={file.content}></img>
<br />
</div>
))}
</div>
);
}
import { useFilePicker } from 'use-file-picker';
import React from 'react';
export default function App() {
const { openFilePicker, filesContent, loading, errors, plainFiles, clear } = useFilePicker({
multiple: true,
readAs: 'DataURL', // availible formats: "Text" | "BinaryString" | "ArrayBuffer" | "DataURL"
// accept: '.ics,.pdf',
accept: ['.json', '.pdf'],
validators: [new FileAmountLimitValidator({ min: 2, max: 3 })],
// readFilesContent: false, // ignores file content
});
if (errors.length) {
return (
<div>
<button onClick={() => openFilePicker()}>Something went wrong, retry! </button>
{errors.map(err => (
<div>
{err.name}: {err.reason}
/* e.g. "name":"FileAmountLimitError", "reason":"MAX_AMOUNT_OF_FILES_EXCEEDED" */
</div>
))}
</div>
);
}
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={() => openFilePicker()}>Select file </button>
<button onClick={() => clear()}>Clear</button>
<br />
Number of selected files:
{plainFiles.length}
<br />
{/* If readAs is set to DataURL, You can display an image */}
{!!filesContent.length && <img src={filesContent[0].content} />}
<br />
{plainFiles.map(file => (
<div key={file.name}>{file.name}</div>
))}
</div>
);
}
You can hook your logic into callbacks that will be fired at specific events during the lifetime of the hook. useFilePicker accepts these callbacks:
These are described in more detail in the Props section.
import { useFilePicker } from 'use-file-picker';
export default function App() {
const { openFilePicker, filesContent, loading, errors, plainFiles, clear } = useFilePicker({
multiple: true,
readAs: 'DataURL',
accept: ['.json', '.pdf'],
onFilesSelected: ({ plainFiles, filesContent, errors }) => {
// this callback is always called, even if there are errors
console.log('onFilesSelected', plainFiles, filesContent, errors);
},
onFilesRejected: ({ errors }) => {
// this callback is called when there were validation errors
console.log('onFilesRejected', errors);
},
onFilesSuccessfullySelected: ({ plainFiles, filesContent }) => {
// this callback is called when there were no validation errors
console.log('onFilesSuccessfullySelected', plainFiles, filesContent);
},
onClear: () => {
// this callback is called when the selection is cleared
console.log('onClear');
},
});
}
useImperativePicker
hook also accepts the callbacks listed above. Additionally, it accepts the onFileRemoved
callback, which is called when a file is removed from the list of selected files.
import { useImperativeFilePicker } from 'use-file-picker';
export default function App() {
const { openFilePicker, filesContent, loading, errors, plainFiles, clear } = useImperativeFilePicker({
onFileRemoved: (removedFile, removedIndex) => {
// this callback is called when a file is removed from the list of selected files
console.log('onFileRemoved', removedFile, removedIndex);
},
});
}
If you want to keep the previously selected files and remove them from the selection, you can use a separate hook called useImperativeFilePicker
that is also exported in this package. For files removal, you can use removeFileByIndex
or removeFileByReference
functions.
import React from 'react';
import { useImperativeFilePicker } from 'use-file-picker';
const Imperative = () => {
const { openFilePicker, filesContent, loading, errors, plainFiles, clear, removeFileByIndex, removeFileByReference } =
useImperativeFilePicker({
multiple: true,
readAs: 'Text',
readFilesContent: true,
});
if (errors.length) {
return (
<div>
<button onClick={() => openFilePicker()}>Something went wrong, retry! </button>
<div style={{ display: 'flex', flexDirection: 'column' }}>
{console.log(errors)}
{errors.map(err => (
<div>
{err.name}: {err.reason}
/* e.g. "name":"FileAmountLimitError", "reason":"MAX_AMOUNT_OF_FILES_EXCEEDED" */
</div>
))}
</div>
</div>
);
}
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={async () => openFilePicker()}>Select file</button>
<button onClick={() => clear()}>Clear</button>
<br />
Amount of selected files:
{plainFiles.length}
<br />
Amount of filesContent:
{filesContent.length}
<br />
{plainFiles.map((file, i) => (
<div>
<div style={{ display: 'flex', alignItems: 'center' }} key={file.name}>
<div>{file.name}</div>
<button style={{ marginLeft: 24 }} onClick={() => removeFileByReference(file)}>
Remove by reference
</button>
<button style={{ marginLeft: 24 }} onClick={() => removeFileByIndex(i)}>
Remove by index
</button>
</div>
<div>{filesContent[i]?.content}</div>
</div>
))}
</div>
);
};
Prop name | Description | Default value | Example values |
---|---|---|---|
multiple | Allow user to pick multiple files at once | true | true, false |
accept | Set type of files that user can choose from the list | "*" | [".png", ".txt"], "image/*", ".txt" |
readAs | Set a return type of filesContent | "Text" | "DataURL", "Text", "BinaryString", "ArrayBuffer" |
readFilesContent | Ignores files content and omits reading process if set to false | true | true, false |
validators | Add validation logic. You can use some of the built-in validators like FileAmountLimitValidator or create your own custom validation logic | [] | [MyValidator, MySecondValidator] |
initializeWithCustomParameters | allows for customization of the input element that is created by the file picker. It accepts a function that takes in the input element as a parameter and can be used to set any desired attributes or styles on the element. | n/a | (input) => input.setAttribute("disabled", "") |
onFilesSelected | A callback function that is called when files are successfully selected. The function is passed an array of objects with information about each successfully selected file | n/a | (data) => console.log(data) |
onFilesSuccessfullySelected | A callback function that is called when files are successfully selected. The function is passed an array of objects with information about each successfully selected file | n/a | (data) => console.log(data) |
onFilesRejected | A callback function that is called when files are rejected due to validation errors or other issues. The function is passed an array of objects with information about each rejected file | n/a | (data) => console.log(data) |
onClear | A callback function that is called when the selection is cleared. | n/a | () => console.log('selection cleared') |
Name | Description |
---|---|
openFilePicker | Opens file selector |
clear | Clears all files and errors |
filesContent | Get files array of type FileContent |
plainFiles | Get array of the File objects |
loading | True if the reading files is in progress, otherwise False |
errors | Get errors array of type FileError if any appears |
useFilePicker has some built-in validators that can be used out of the box. These are:
useFilePicker allows for injection of custom validation logic. Validation is divided into two steps:
interface Validator {
validateBeforeParsing(config: UseFilePickerConfig, plainFiles: File[]): Promise<void>;
validateAfterParsing(config: UseFilePickerConfig, file: FileWithPath, reader: FileReader): Promise<void>;
}
Validators must return Promise object - resolved promise means that file passed validation, rejected promise means that file did not pass.
Since version 2.0, validators also have optional callback handlers that will be run when an important event occurs during the selection process. These are:
/**
* lifecycle method called after user selection (regardless of validation result)
*/
onFilesSelected(
_data: SelectedFilesOrErrors<ExtractContentTypeFromConfig<ConfigType>, CustomErrors>
): Promise<void> | void {}
/**
* lifecycle method called after successful validation
*/
onFilesSuccessfullySelected(_data: SelectedFiles<ExtractContentTypeFromConfig<ConfigType>>): Promise<void> | void {}
/**
* lifecycle method called after failed validation
*/
onFilesRejected(_data: FileErrors<CustomErrors>): Promise<void> | void {}
/**
* lifecycle method called after the selection is cleared
*/
onClear(): Promise<void> | void {}
/**
* This method is called when file is removed from the list of selected files.
* Invoked only by the useImperativeFilePicker hook
* @param _removedFile removed file
* @param _removedIndex index of removed file
*/
onFileRemoved(_removedFile: File, _removedIndex: number): Promise<void> | void {}
/**
* validateBeforeParsing allows the user to select only an even number of files
* validateAfterParsing allows the user to select only files that have not been modified in the last 24 hours
*/
class CustomValidator extends Validator {
async validateBeforeParsing(config: ConfigType, plainFiles: File) {
return new Promise<void>((res, rej) => (plainFiles.length % 2 === 0 ? res() : rej({ oddNumberOfFiles: true })));
}
async validateAfterParsing(config: ConfigType, file: FileWithPath, reader: FileReader) {
return new Promise<void>((res, rej) =>
file.lastModified < new Date().getTime() - 24 * 60 * 60 * 1000
? res()
: rej({ fileRecentlyModified: true, lastModified: file.lastModified })
);
}
onFilesSuccessfullySelected(data: SelectedFiles<ExtractContentTypeFromConfig<ConfigType>>) {
console.log(data);
}
}
👤 Milosz Jankiewicz
👤 Kamil Planer
Contributions, issues and feature requests are welcome!
Feel free to check the issues page.
Give a ⭐️ if this project helped you!
FAQs
Simple react hook to open browser file selector.
The npm package use-file-picker receives a total of 16,086 weekly downloads. As such, use-file-picker popularity was classified as popular.
We found that use-file-picker demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
Research
Security News
The Socket Research team found this npm package includes code for collecting sensitive developer information, including your operating system username, Git username, and Git email.
Security News
OpenJS is warning of social engineering takeovers targeting open source projects after receiving a credible attempt on the foundation.