Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Uploading Files with React.js

This guide covers how to upload a file with React and how to use the Fetch API to upload files.

Nov 15, 2020 • 9 Minute Read

Introduction

You may not have ever handled file uploads in React or any other technologies, but there is a high possibility you'll encounter the need for it, whether tor update profile photos of users, CSV files, or PDFs, to mention but a few. In this guide, you'll learn how to upload files in your React apps.

Set Up an App

To get started, run the following command in your terminal or visit https://react.new to get a fully configured React development environment via https://codesandbox.io.

      npx create-react-app <YOUR_APP_NAME>
    

<YOUR_APP_NAME> refers to your preferred app name.

Next, create a simple component that has a file input with an upload button.

      import React from 'react';

function FileUploadPage(){
	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

Add State

Now add some state to your app to contain information about the file selected by the user.

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

selectedFile contains information on the currently picked file.

isFilePicked determines if a file has been picked or not.

Now implement the handleSubmission and changeHandler event handlers, then add a conditional to display details of the currently selected file in state.

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		setIsSelected(true);
	};

	const handleSubmission = () => {
	};

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

Event.target.files is an object that contains the details of files selected to be uploaded in a form.

The currently selected file object also looks as follows.

      {
		lastModified: 1588350162449
		lastModifiedDate: Fri May 01 2020 17:22:42 GMT+0100 (British Summer Time) {} // Date object
		name: "Pluralsight_logo.png"
		size: 68317
		type: "image/png"
		webkitRelativePath: ""
		__proto__: File
}
    

Now add the conditional display logic to give the user details of the file.

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		setIsSelected(true);
	};

	const handleSubmission = () => {
	};

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			{isSelected ? (
				<div>
					<p>Filename: {selectedFile.name}</p>
					<p>Filetype: {selectedFile.type}</p>
					<p>Size in bytes: {selectedFile.size}</p>
					<p>
						lastModifiedDate:{' '}
						{selectedFile.lastModifiedDate.toLocaleDateString()}
					</p>
				</div>
			) : (
				<p>Select a file to show details</p>
			)}
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

Upload a File with Fetch

The Fetch API can be used to implement file uploads, or you can also use a library such as Axios to implement the upload logic. Implement the onClick handler, as shown below, to handle the file upload.

There's a free service that enables file uploads via their API, so go ahead and signup here to obtain an API key.

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		setIsSelected(true);
	};

	const handleSubmission = () => {
		const formData = new FormData();

		formData.append('File', selectedFile);

		fetch(
			'https://freeimage.host/api/1/upload?key=<YOUR_API_KEY>',
			{
				method: 'POST',
				body: formData,
			}
		)
			.then((response) => response.json())
			.then((result) => {
				console.log('Success:', result);
			})
			.catch((error) => {
				console.error('Error:', error);
			});
	};
	};

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			{isSelected ? (
				<div>
					<p>Filename: {selectedFile.name}</p>
					<p>Filetype: {selectedFile.type}</p>
					<p>Size in bytes: {selectedFile.size}</p>
					<p>
						lastModifiedDate:{' '}
						{selectedFile.lastModifiedDate.toLocaleDateString()}
					</p>
				</div>
			) : (
				<p>Select a file to show details</p>
			)}
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

What happened here? You used the fetch API together with the FormData native Javascript API to post the file to the fileserver.

A successful post to the server should result in the following response.

      {
							"status_code": 200,
							"success": {
								"message": "image uploaded",
								"code": 200
							},
							"image": {
								"name": "example",
								"extension": "png",
								"size": 53237,
								"width": 1151,
								"height": 898,
								"date": "2020-11-11 15:32:33",
								"date_gmt": "2020-11-11 19:32:33",
								"storage_id": null,
								"description": null,
								"nsfw": "0",
								"md5": "d973298h0d722c956c3629870299735830",
								"storage": "datefolder",
								"original_filename": "pluralsight_logo.png",
								"original_exifdata": null,
								"views": "0",
								"id_encoded": "L",
								"filename": "pluralsight_logo.png",
								"ratio": 1.2817371937639,
								"size_formatted": "52 KB",
								"mime": "image/png",
								"bits": 8,
								"channels": null,
								"url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.png",
								"url_viewer": "http://freeimage.host/image/L",
								"thumb": {
									"filename": "example.th.png",
									"name": "example.th",
									"width": 160,
									"height": 160,
									"ratio": 1,
									"size": 17848,
									"size_formatted": "17.4 KB",
									"mime": "image/png",
									"extension": "png",
									"bits": 8,
									"channels": null,
									"url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.th.png"
								},
								"medium": {
									"filename": "pluralsight_logo.md.png",
									"name": "pluralsight_logo.md",
									"width": 500,
									"height": 390,
									"ratio": 1.2820512820513,
									"size": 104448,
									"size_formatted": "102 KB",
									"mime": "image/png",
									"extension": "png",
									"bits": 8,
									"channels": null,
									"url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.md.png"
								},
								"views_label": "views",
								"display_url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.md.png",
								"how_long_ago": "moments ago"
							},
							"status_txt": "OK"
						}
    

Conclusion

And that's a wrap. In this guide, you learned how to upload a file with React and how to use the Fetch API to upload files. If you'd like to read more on the Fetch API and the formData API, the following resources will help:

  1. https://developer.mozilla.org/en-US/docs/Web/API/FormData

  2. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

  3. /content/ps/en/resources/blog/guides/using-fetch-with-github-api-v3.html

Learn More

Check out these React courses from Pluralsight to continue learning: