People working on React.js project or have been working as MERN Stack developer, goes in problem in file upload or image upload since they are supposed to send file information rather than just JSON text data to the server. Sometimes they are struck on image upload feature which seems confusing to work with but in reality it isn’t complex and easy to implement.
There are many ways of uploading images in the server. There are always package we can use to upload Image. There is no best way to upload an Image, I would rather say if anything satisfies your need you can just use it; don’t have to make it hard. In this time, there are a lot of frameworks and everything and if your condition for the project or app satisfies with just HTML and CSS just use, don’t have to go through all the frameworks and everything.
How file uploads works in React is that we have to send the file to the server and server will be storing the file and will be returning the name of the file which will be stored in the database. And when user tries to fetch the image, the database will provide the name of the file and we will be fetching the image from the server using the name of the file.
Let’s learn how it works, firstly user selects an image from <input type="file" /> provided by HTML. This form will take the input type of file not only image but also supports other types of files like pdf, docs, etc, but we are not going to discuss more about it. So we will be using input type of file. When we select the image, the image temporary file is created and it’s name, and type of the image. After getting name type we can change the name while saving to server mostly people use DateTime and edit the name which will be store in the database.
Remember in database we are not going to save our image, what we will be storing is the name of the file stored somewhere in the database. So, we will be sending the image to the server and server will be storing the image in the server and will be returning name which will be stored in database and when user try to fetch the image, the database will provide the name of the file and we will be fetching the image from the server using the name of the file.
And when input type selects the image, a temporary image file is created which we will be moving to the server. So we will be going to send file and storing to the server and which will returns the name and the name is going to be stored in the database. But we will be looking for sending image to the server side. And in server side there are many packages which will help you store the image in the server. You can use package like multer, formidable where we can store the image and can change name and structure like image file through it.
At first, let’s create an React Application.
export default function App() {
return (
<div>
<form>
<input type="file" />
<input type="submit" value="Send Image" />
</form>
</div>
)}
I am skipping the styling part of the component. We won’t be discussing about it, we will be creating a simple form for sending data to the server. So it creates a form which have an input type of file and there is a input type of submit which handles the form submit.
import { useState } from 'react'
const [image, setImage] = useState();
Here we are creating an hook called useState to store the image file information and which spoiler-alert, we are going to sent to the backend. So, now we have imported useState from react and have created a useState hook. I hope everyone knows about useState hook, basically the first state is an image which initial value is decleared inside the useState() which we have left empty. And now we are going to store image in it using setImage hook which is used to update the image.
so we will be doing something like this
const onChangeEvent = (e) => {
e.preventDefault(); // which stops form to get submitted
setImage(e.target.files[0]);
}
export default function App() {
return (
...same as above
<input type="file" onChange={onChangeEvent} />
)
}
here e is the event and target of files which can have multiple images for this we have to included multipart-enctype we are skipping it and it will end up having our image stored in the image created by useState hook. So, whenever we change the input type the hooks also changed with the latest images. So we have our image stored on the hook and we will be sending the image from the hook. We will be sending data using FormData, where we will append the image data to it.
const sendData = (e) => {
e.preventDefault();
const form = new FormData();
form.append('image', image);
fetch('http://localhost:5000/upload', {
method: 'POST',
body: form
});
}
export default function App() {
<form onSubmit={sendData}>
...
</form>
}
voila, Now the data has been managed and ready to be sent to backend and it is stored in form and we can use fetch or axios method to send the image data to the server.
The final code will look something like this:
import { useState } from 'react'
export default function App() {
const [image, setImage] = useState();
const onChangeEvent = (e) => {
e.preventDefault(); // which stops form to get submitted
setImage(e.target.files[0]);
}
const sendData = (e) => {
e.preventDefault();
const form = new FormData();
form.append('image', image);
fetch('http://localhost:5000/upload', {
method: 'POST',
body: form
});
}
return (
<div>
<form onSubmit={sendData}>
<input type="file" onChange={onChangeEvent} />
<input type="submit" value="SEND DATA" />
</form>
</div>
)
}