File Upload in react with FilePond (2024)

Dheeraj

Posted on

File Upload in react with FilePond (3) File Upload in react with FilePond (4) File Upload in react with FilePond (5) File Upload in react with FilePond (6) File Upload in react with FilePond (7)

#react #typescript #tutorial #javascript

FilePond is javascript library that that can upload almost anything you through at it. It is one of the best and all rounded file uploading solutions out there IMO.

In this tutorial, we'll create a simple file upload component and configure it, with react, hooks and typescript.

Getting the dependencies

Let's start by adding filepond and it's react implementation to our project dependency.

npm install react-filepond filepond --save

FilePond comes with a lot of extensions that you can use to add extra functionalities like file size validation, image preview etc.. But For now this is just enough to get us started.

Creating your react component

Let's create a component, which will have a prop as a callback once the upload is complete, and on for the list of accepted file types.

1 import React from 'react';2 3 interface FileUploaderProps {4 onUploadComplete: () => void;5 fileTypes: string[];5 }6 7 export const FileUploader = (props: FileUploaderProps) => {8 9 return (10 <div className={styles.wrapper}>11 // filePond will go here ..12 </div>13 )14 }15 

Introducing filepond

Now lets bring file pond into the mix.

First we import FilePond along with File type def from react-filepond.

2 import { FilePond, File } from 'react-filepond';

now we need a state to store the file once it's uploaded.

This state we will pass to the file prop of the filePond component and the setFiles dispatch will be passed to onupdatefiles prop.

8 export const FileUploader = (props: FileUploaderProps) => {9 const [files, setFiles] = useState<File[]>([]);

Add FilePond to our wrapper with some basic props.

11 return (12 <div className={styles.wrapper}>13 <FilePond14 files={files}15 onupdatefiles={setFiles}16 allowMultiple17 server="/api" // your file upload api18 name="files"19 />20 </div>21 )

lets also add the css to get the awesome file upload styles going.

1 import React, { useState } from 'react';2 import { FilePond, File } from 'react-filepond';3 4 import 'filepond/dist/filepond.min.css';

Well we are almost done. Let's add few more tweaks.

Adding drag and drop

Pass dropOnPage to add drag and drop files, additionally you can add dropValidation flag to validate files on drop.

11 return (12 <div className={styles.wrapper}>13 <FilePond14 files={files}15 onupdatefiles={setFiles}16 allowMultiple={false}17 dropOnPage18 server="/api" // your file upload api19 name="files"20 dropOnPage21 dropValidation22 />23 </div>24 )

Adding pluggings

File pond supports a ton of plugging, you can find a full list over here.

For now, let's add file type validation plugin.

First we install the plugin.

npm install filepond-plugin-file-validate-size

Then, import registerPlugin from react-filepond.

2 import { FilePond, File, registerPlugin } from 'react-filepond';

now import filepond-plugin-file-validate-size and register the plugin with filePond

1 import React, { useState } from 'react';2 import { FilePond, File, registerPlugin } from 'react-filepond';3 4 import FilePondPluginFileValidateSize from 'filepond-plugin-file-validate-size';56 registerPlugin(FilePondPluginFileValidateType);7 8 import 'filepond/dist/filepond.min.css';

FilePond component should now take in a props called acceptedFileTypes which takes in array of MIME types. you can get a list of common MIME types here.

Since we are getting the fileTypes as a prop, lets pass it here.

11 return (12 <div className={styles.wrapper}>13 <FilePond14 files={files}15 onupdatefiles={setFiles}16 allowMultiple={false}17 dropOnPage18 server="/api" // your file upload api19 name="files"20 dropOnPage21 dropValidation22 acceptedFileTypes={props.fileTypes}23 />24 </div>25 )

You can even go a bit deeper and configure the server prop to add more control over how the files are handled.

Configuring server

The server prop takes in a the API url as a string or an configuration object.

Let's add some basic configurations.

11 return (12 <div className={styles.wrapper}>13 <FilePond14 files={files}15 onupdatefiles={setFiles}16 allowMultiple={false}17 dropOnPage18 server={{19 process: {20 url: "/api/url",21 headers: {22 Authorization: `Bearer eyJH18ui0...`,23 },24 ondata: (formData) => {25 formData.append('extraField', value);26 return formData;27 },28 onload: () => {29 props.onUploadComplete();30 },31 }32 }}33 name="files"34 dropOnPage35 dropValidation36 acceptedFileTypes={props.fileTypes}37 />38 </div>39 )

ondata callback let's us add extra fields to the post request's formData.

onload is called once the file upload is completed and server responds OK. Now this is where we call our onUploadComplete prop which we are passing on to our component.

Find more on server configurations, here.

That’s it!!

Finally the component

1 import React, { useState } from 'react';2 import { FilePond, File, registerPlugin } from 'react-filepond';3 4 import FilePondPluginFileValidateSize from 'filepond-plugin-file-validate-size';56 registerPlugin(FilePondPluginFileValidateType);7 8 import 'filepond/dist/filepond.min.css';910 export const FileUploader = (props: FileUploaderProps) => {11 const [files, setFiles] = useState<File[]>([]);1213 return (14 <div className={styles.wrapper}>15 <FilePond16 files={files}17 onupdatefiles={setFiles}18 allowMultiple={false}19 dropOnPage20 server={{21 process: {22 url: "/api/url",23 headers: {24 Authorization: `Bearer eyJH18ui0...`,25 },26 ondata: (formData) => {27 formData.append('extraField', value);28 return formData;29 },30 onload: () => {31 props.onUploadComplete();32 },33 }34 }}35 name="files"36 dropOnPage37 dropValidation38 acceptedFileTypes={props.fileTypes}39 />40 </div>41 )42 }43

Well, that's pretty much it for this tutorial, but the features and configuration for filePond dosen't end there, check out their documentation for more.

Happy coding ;)

File Upload in react with FilePond (2024)
Top Articles
How to Invest in Private Equity - SmartAsset
Estate Planning: Wills Vs Trusts | ChooseFI
Menards Thermal Fuse
It may surround a charged particle Crossword Clue
Lifebridge Healthstream
La connexion à Mon Compte
Grange Display Calculator
Mndot Road Closures
Truist Drive Through Hours
Azeroth Pilot Reloaded - Addons - World of Warcraft
Best Pawn Shops Near Me
4Chan Louisville
Urban Dictionary Fov
Miss America Voy Forum
Craiglist Galveston
Define Percosivism
Wal-Mart 140 Supercenter Products
Imagetrend Inc, 20855 Kensington Blvd, Lakeville, MN 55044, US - MapQuest
Craigslist Portland Oregon Motorcycles
Golden Abyss - Chapter 5 - Lunar_Angel
Water Trends Inferno Pool Cleaner
Yard Goats Score
Days Until Oct 8
Orange Pill 44 291
Craigslist Alo
Bidrl.com Visalia
Mikayla Campinos: Unveiling The Truth Behind The Leaked Content
Uno Fall 2023 Calendar
140000 Kilometers To Miles
Ultra Clear Epoxy Instructions
Timothy Kremchek Net Worth
Agematch Com Member Login
New York Rangers Hfboards
Gets Less Antsy Crossword Clue
How are you feeling? Vocabulary & expressions to answer this common question!
Toth Boer Goats
Cheetah Pitbull For Sale
Improving curriculum alignment and achieving learning goals by making the curriculum visible | Semantic Scholar
Panorama Charter Portal
Skyward Marshfield
Postgraduate | Student Recruitment
Lyndie Irons And Pat Tenore
Rs3 Nature Spirit Quick Guide
Peace Sign Drawing Reference
56X40X25Cm
Iupui Course Search
This Doctor Was Vilified After Contracting Ebola. Now He Sees History Repeating Itself With Coronavirus
The Many Faces of the Craigslist Killer
877-552-2666
Market Place Tulsa Ok
The Love Life Of Kelsey Asbille: A Comprehensive Guide To Her Relationships
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6308

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.