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

Clicking on a JQuery dropdown menu will always result in it staying open

After creating a dropdown menu click, I noticed some strange behavior. When I click the dropdown button, the menu appears as expected. However, if I move my cursor away without clicking the button again, the dropdown menu disappears and behaves like a hove ...

Creating a personalized dropdown menu in react-draft-wysiwyg: A step-by-step guide

I am looking to incorporate a custom dropdown menu into the toolbar section. Here is an image that shows what I want for the dropdown menu. Can this be done? <img src="https://i.imgur.com/OhYeFsL.png" alt="Dropdown menu editor"> You can view a mor ...

Using Express to insert data into a MongoDB database

Having trouble inserting data into MongoDB using Express as it's always storing blank. Also, no console logs are being printed: The URL I'm hitting after starting the server is http://localhost:3000/posts?title=test&link=http://test.com An ...

Is there a way for me to retrieve information from a different website using a URL, similar to how Digg's submit button works

Currently, I am in the process of developing a website with the cakePHP framework. As a beginner in PHP and web programming, my goal is to implement a feature similar to Digg's submit button. This functionality would involve inputting a URL, which the ...

Array of Ascending Progress Indicators

I currently have a progress bar that I'm happy with, but I want to enhance it by incorporating stacked progress bars. My aim is to have the progress bar behave in the following way when an option is selected: https://i.stack.imgur.com/Pw9AH.png & ...

What is the best way to save a JavaScript variable in local storage?

I am facing an issue with a JavaScript variable named addNumber. This variable is responsible for adding 1 to a div every time a button is clicked. However, the problem arises when I navigate between different pages on my website - the counter resets back ...

Issue with directive not activating when attribute is changed

I am facing an issue with my website where users can make selections from two dropdowns, and based on those values, attributes are sent to directives for a corresponding function to be called. The problem I'm encountering is that the directives are n ...

Having trouble retrieving the ID of a Mongoose.Model instance in MongoDB using Mongoose.js

Currently, I am utilizing a simple Mongoose.Model instance find() to retrieve a random document from an employee collection. However, I am encountering difficulty in obtaining its ID. When I view the document contents using MongoLab, I am presented with th ...

Utilizing jQuery to iterate over dynamically generated elements sharing a common class

Whenever I click a button, numerous div elements are dynamically created. <table> <tbody id="ProductDetail"></tbody> </table> These dynamically created divs have an associated Amount value that is added upon creation. funtion ...

Determining the best times to utilize Grid items for alignment and justification versus when to avoid using them

I am wondering about the appropriate use of Grid item in order to utilize the props of the Grid container such as justify or alignItems. I initially thought that these attributes could only be applied to the Grid item within the Grid container, but my exam ...

Issue with Angular: Unable to properly sort data while modifying queryParams

Within the component.ts file: export class TabsComponent implements OnInit { constructor( private store$: Store<UsersState>, private router: ActivatedRoute ) {} ngOnInit(): void { this.onFilterByIncome(); this.router.queryParam ...

How can you refresh a single element within an array using Angular.js?

System Background: The application is developed using Angular for the front end with routing capabilities, and Node.js, Express, MongoDB, and Mongoose for the back end. Within a controller, there is an array named $scope.array=[]; that is populated throug ...

Adjust the autofocus to activate once the select option has been chosen

Is there a way to automatically move the cursor after selecting an option from a form select? <select name="id" class="form-control"> <option>1</option> <option>2</option> <option>3</option&g ...

Encountered an error with symbol '@' while utilizing ES6 decorators

I have recently set up a React project and now I'm attempting to integrate MobX into it. This requires using decorators such as: @observable However, when I try to implement this, I encounter the following error: https://github.com/mobxjs/mobx Mod ...

Is it considered poor design to pass a function two levels deep? Are there other possible alternatives to achieve the same outcome?

I am currently working on a scenario involving componentA, which also contains another componentB with buttons that need to update the scene. My initial thought was to pass a function from the scene to componentB through componentA, but since I am new to ...

The console log is not being displayed in my Redux reducer and it is returning an undefined

I'm facing an issue with my Redux application after integrating JWT into my Nest API. Below is the code snippet from my reducer: export default function reducer(state = {}, action) { switch (action.type) { case 'USER_LOGIN_SUCCESS&apo ...

Res.render() is failing to display content

I'm facing an issue with my express route where it's not rendering a jade template properly. If I provide the wrong jade template string, I get the usual error indicating that the file couldn't be found to render in the browser. However, wh ...

Disable the automatic scrolling feature of the daisyUI carousel when moving between slides

I recently implemented a carousel with indicator buttons from daisyUI in my Nextjs application. Unfortunately, I noticed that when clicking on an indicator button, not only does it switch slides but it also scrolls the page so that the top of the slide ali ...

Set a delay for an AJAX request using jQuery

Is it possible to incorporate a setTimeout function into this ajax call? Here's the code snippet: jQuery.ajax({ type : "POST", url : dir+"all/money/myFile.php", data : "page="+data.replace(/\&/g, '^'), suc ...

Efficient File Upload Feature Compatible with all Browsers, Including Internet Explorer versions 7, 8, and 9

Can someone assist me with a problem I'm facing? I need a code script that enables multiple file uploading on all browsers. While HTML5 supports Chrome and Mozilla Firefox, it does not support IE. I am looking for a script/jquery solution that works ...