How to store images to server in base64 string format
In Today's time, many web application revolves around images or images are the core part of the application and handling image upload and storing on the server and in the database has been a complex task from the beginning.
In this article, we will have a look at the Reactjs component to convert image files to base64 string and storing that string on the server-side without maintaining a separate folder for storing uploaded images.
Command to install the package:
npm install react-file-base64
Advantages:
- It doesn't require setting enctype="multipart/form-data" for uploading image files to the server.
- It does not require to set headers: {Content-Type:'application/JSON'} while making a post request to API and sending an image to API.
- On the server-side, it doesn't require to maintain a separate folder to store all image to it.
- It doesn't require setting the file path to the specified folder.
- It doesn't require setting the file name by adding date and time to its name and then storing the image in a folder.
- It converts an image to a simple base64 string which can be treated the same as a normal string.
Let's Get Started
First, we have to create a react application
npx create-react-app testingbasecd testingbasenpm install react-file-base64npm start
Implementing FileBase as below
App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useState} from 'react'; | |
import FileBase from 'react-file-base64' | |
import './App.css'; | |
function App() { | |
const [imageString, setImageString] = useState({}) | |
console.log(imageString); | |
return ( | |
<div className="app"> | |
<h1>Image to base64 String</h1> | |
<FileBase multiple={false} onDone = {(temp) => setImageString(temp)}></FileBase> | |
<div> | |
{imageString.base64 ? <img className="displayimg" alt="displaying" src = {imageString.base64} /> : null } | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Code Breakdown
First, we have to import FileBase implement same as we import and implement all other packages.
FileBase mainly has two component:
- multiple(Boolean) : It takes boolean value(true/false) whether to upload multiple files.
- onDone(Function): onDone function is called after we have selected the file which is to be uploaded and has the callBack function which returns us an object describing the image as shown below.
To display an image it just requires to pass the base64 image string to the src attribute of the image tag as shown
FileBase returns many values in object and some important values that are required by us are
- name: It describes the name of the image.
- type : It describes type of image(jpg/jpeg/png etc.).
- size: It describes the size of the file.
- base64: It describes a string representation of an image. This is the value that we require to send to the server and to store in the database.
Sending the image to Server
By simple post method, we can send data to the server, we don't have to worry about request headers because it is treated as a normal string and doesn't require any special treatment.
server.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const cors = require('cors'); | |
const app = express(); | |
app.use(bodyParser.json({limit:"30mb"})); | |
app.use(bodyParser.urlencoded({ extended: true })); | |
app.use(cors()); | |
const port = 9000; | |
const imgarray = [] | |
app.post('/receive',async (req,res) =>{ | |
const received = req.body; | |
imgarray.push(received.base64); | |
console.log(imgarray); | |
res.send(imgarray); | |
// await dbSchema.create(received, (err, data) =>{ | |
// if(err){ | |
// res.status(500).send(err); | |
// } | |
// else{ | |
// res.status(201).send(data); | |
// } | |
// }) | |
}) | |
app.listen(port,() => (console.log(`Listening on ${port}`))); |
As we are receiving the data from the frontend and we are just saving the base64 string of the image into an array(It can be saved to the database in a save manner as in array), and we are sending back the array in response and displaying all images retrieving from the server. (*in Final Output)
*In Database set the image field type to String and save the base64 string.
Final Output
Conclusion:
A simple and secure concept of storing the image into base64 string format and processing it as a normal string which makes file handling very easy.
It doesn't require any complex way to store and process files on the server.
Interesting!!
ReplyDeleteInformative content
ReplyDeleteFascinating stuff
ReplyDelete