Author avatar

Desmond Nyamador

Uploading Files with React.js

Desmond Nyamador

  • Nov 15, 2020
  • 8 Min read
  • 192 Views
  • Nov 15, 2020
  • 8 Min read
  • 192 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

1
npx create-react-app <YOUR_APP_NAME>
jsx

<YOUR_APP_NAME> refers to your preferred app name.

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

1
2
3
4
5
6
7
8
9
10
11
12
import React from 'react';

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

Add State

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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>
	)
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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>
	)
}
jsx

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.

1
2
3
4
5
6
7
8
9
{
		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
}
jsx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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>
	)
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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>
	)
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{
							"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"
						}
json

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:

5