Attempting to display a base-64 encoded image in a Next.js application

After following this method, I successfully uploaded my image as a string:

             const [image, setImage] = useState("");
            //------------------^^^^^^^^^^^^^^^^-------------------------

            const handleImage = (e) => {
                console.log("Handle image called");
                const selectedFile = e.target.files[0];
                console.log("Selected file:", selectedFile);
                if (selectedFile) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const imageData = e.target.result;
                        console.log("imageData: ", imageData);
                        setImage(imageData); // Store the Base64-encoded image data
                    };
                    reader.readAsDataURL(selectedFile);
                }
            };

Now, in another file, I retrieved data from mongo which includes an image encoded in base 64. However, when trying to render the image, only the alt text is showing:

                    const petCards = petData.map((pet, index) => (
                <div className="card-results-find" key={index}>
                    <div className="img-card-find">
                        <Image
                            src={`data:image/jpeg;base64,${pet.image}`}
     //I have also tried {petData.image} for src
                            alt={pet.catName}
                            layout="fill"
                        />
                    </div>

                //css:

               .img-card-find {
                position: relative;
                width: 100%;
                height: 90vh;
               }

The petData.image contains something like this: image EDIT I extracted the image data like this:

const imageData = imageBase64.split(",")[1];

Answer №1

Revamp the method of sending data to the backend by simply sending the URL:

                const handleImage = (e) => {
                console.log("Handle image called");
                const selectedFile = e.target.files[0];
                console.log("Selected file:", selectedFile);
                if (selectedFile) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const imageData = e.target.result;
                        console.log("imageData: ", imageData);

                        const dataURL = `data:image/jpeg;base64,${btoa(imageData)}`;
                        console.log("dataURL: ", dataURL);

                        setImage(dataURL);
                    };
                    reader.readAsBinaryString(selectedFile);
                }
            };

Additionally, on the server side, refrain from following this process: const imageData = imageBase64.split(",")[1]; and encode the image like so: const encodedImageData = encodeURIComponent(imageData);

This action will then save your image to the database as a URL.

Subsequently, when retrieving the image:

        <Image
                            src={decodeURIComponent(pet.imageSrc)}
                            alt={pet.petName} 
                            width={300}
                            height={200}
                        />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

Keep your data safe and protected within a Node CLI application

Currently developing a NodeJS command-line application that interacts with an API to provide data to users. To access the public API, users need an API token. The CLI will be globally installed on users' machines using npm i -g super-cool-api-cli. Up ...

Leveraging AJAX to transmit a JavaScript variable to PHP within the same webpage

I have a webpage where I want to update a PHP variable based on the value of a name attribute when a user clicks on a link. Here is an example of what I am attempting to accomplish: // PHP <?php $jsVar = $_POST['jsVar']; echo $jsVar; ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

Sharing session data between controller and view in an Express.js application

When logging in with the code below in the express controller to redirect to the main page: req.session.user = user.userLogin; if (req.session.user=='Admin') { global.loggedAdmin = user.userLogin; } else { global.loggedUser = user.us ...

What is the best way to center text on an HTML canvas?

Is it possible to center an h1 tag in the middle of an HTML canvas using either JavaScript or HTML? I already have a CSS file for canvas styles. HTML <body> <canvas id="myCanvas"></canvas> <script src="canvas.js"></scri ...

User input determines the path of Iron Route in Meteor

A requirement is to execute a function that prompts the user for input and then navigates to that specified value. For instance, if the inserted value is: https://www.youtube.com/watch?v=_ZiN_NqT-Us The intended destination URL should be: download?u ...

Preventing Duplicate Form Submissions in Rails 5 using jQuery

As a coding novice, I'm currently working on my Rails 5 app and implementing image cropping and uploading directly to AWS S3 from the client side using blueimp/jQuery-File-Upload. However, I have encountered an issue where multiple form submissions o ...

Firebase 9: Access Denied - Realtime Database Security Breach

Currently working on a chat application using Vue3 and Firebase 9, everything is functioning well except for the delete function. An error message appears in the console: @firebase/database: FIREBASE WARNING: set at /message/-MzxBJXezscUw4PbEAys failed: pe ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...

What steps can be taken to guarantee that React updates occur in the correct order?

I'm currently working on developing a multi-select dropdown and facing the issue of hiding the options once a user selects one. The problem arises when I try to update the selectedCategoriesData state and then hide the dropdown using setShowCategories ...

The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the er ...

How can you use a selector to filter Cheerio objects within an `each` loop?

As I work on parsing a basic webpage using Cheerio, I began to wonder about the possibilities at hand: Consider a content structure like this: <tr class="human"> <td class="event"><a>event1</a></td> <td class="nam ...

Tips for utilizing Redux toolkit dispatch within Next.js when using SSG or SSR

I've been struggling for a while to resolve my problems with using Hook like useDispatch in either getStaticProps or getServerSideProps. I'm utilizing redux-toolkit for state management and also working with Next.js, but encountered an error when ...

Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control. I am looking to validate the text entered by users as alphanumeric characters and spaces only. Allowed characters are: a-z, A-Z, 0-9, and space. I want to perform this validation using Java ...

Struggling with preloading information in Next.js

I have set up a simple dummy API that provides an array of objects with dummy data: // api/projectsdata.js export default function handler(req, res) { res.status(200).json([{...},{...},{...}] } The fetch API I am using looks ...

What are some effective techniques for handling asynchronous operations while utilizing [displayWith] in an autocomplete

In my angular reactive form, I am struggling with an autocomplete functionality. I want to show the name (myObject.name) but use the ID (myObject.id) as the value. However, when the form is populated with existing values, there is a delay in retrieving th ...

Is there a way to dynamically adjust @keyframes properties through JavaScript?

I am looking to dynamically change the top value of the keyframes based on a JavaScript variable x. While I have experience changing CSS with JavaScript, this particular challenge has me stumped. Code: var x = Math.floor((Math.random() * 1080) + 1); ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...