React hook allowing you to select files from your computer filesystem via a trigger method
·
Report Bug
·
Request Feature
This hook is designed to allow you to trigger the browser's open file dialog so that files can be selected and used within your React application. The hook returns an async trigger() method which returns the corresponding selected HTML file objects.
Install the package into your application via GitHub Package Manager
npm install @rsispal/use-browser-open-file-dialogBelow is a minimal example showing how to use this package:
export const HomePage = () => {
const ofdField = useRef(null); // Set the initial value of the ref to null
const [trigger] = useBrowserOpenFileDialog(ofdField, ".txt", true);
const handleClick = async () => {
const files = await trigger(); // Returns corresponding HTML File objects based on user selectioj
files.forEach(async (file: File) =>
console.log(`FILE DETAILS`, {
filename: file.name,
lastModified: file.lastModified,
size: file.size,
content: await file.text(), // File data can be read here as required as a blob, text, arrayBuffer or stream
})
);
};
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<h1>Example</h1>
<button data-testid="trigger-upload-btn" onClick={handleClick}>
Select Files
</button>
<OpenFileDialogUploadField fieldRef={ofdField} hidden={true} />
</div>
);
};An example Single Page Application is also provided to demonstrate the hook's usage. Follow the steps below to run this:
- Clone the repo
git clone https://github.com/rsispal/use-browser-open-file-dialog.git
- Install NPM packages
npm install
- Build the hook source and example locally
npm run build
- Run the example and visit the localhost URL shown in your terminal
npm run start
See the open issues for a list of proposed features (and known issues).
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.
Project Link: https://github.com/rsispal/use-browser-open-file-dialog