Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Thu Mar 23 2023

How to upload and reading files in React

In this guide we will create a simple component that are uploading files to a server. And then we will create a component that are reading an image in form of base64 from a server and displaying it in a <img /> tag.

Create our upload component

import axios from "axios"; import { useState } from "react"; export const FileUpload = () => { const [selectedFile, setSelectedFile] = useState(null); const onFileChoose = (event) => setSelectedFile(event.target.files[0]); const onFileUpload = () => { const formData = new FormData(); formData.append("file", selectedFile, selectedFile.name); axios.post(`${API_URL}/upload`, formData); }; return ( <div> <input onChange={onFileChoose} type="file" /> <button disabled={!selectedFile} onClick={onFileUpload}> Upload file </button> </div> ); };

If you want to test it out with a server, go and check out this article where we are creating a REST API which handles file uploads and retrieving files. If you are having CORS issues, go and have a look at this simple guide for CORS handling in express.

Display base64 image

import axios from "axios"; import { useState } from "react"; const base64ToBlob = (base64) => { const byteCharacters = window.atob(base64); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); return new Blob([byteArray]); }; export const Img = ({ url }) => { const [image, setImage] = useState(null); useEffect(() => { axios .get(url) .then((response) => setImage(base64ToBlob(response.data))); }, []); if (!image) { return null; } return <img alt="image" src={URL.createObjectURL(image)} />; };

So there we have it. We are loading a base64 representation of an image, converting it into a Blob and then creating an object url out of it. If you want the full implementation of both client and server, check this artice out.

Outro

In this guide we created a component for file uploads that we can use in our React applications for storing files. We also created a component which retrieves a base64 image and converted it into a url that we could add to our <img /> src.

Hope you found this tutorial useful. As mentioned already in the article, we have a related post for setting up a REST API for storing/retrieving the actual files in NodeJs. Read it here.

signatureThu Mar 23 2023
See all our articles