PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 3, 2022

[FIXED] How to show image in react using the data from mysql created by xampp

 July 03, 2022     mysql, reactjs, xampp     No comments   

Issue

I have used nodejs and xampp to create a server. In Xampp for the image, i have used Blob long. Using react as frontend, I fetched the image. I assigned this img data to the image src but its not displaying. Inspect on the image src, show a long series of numbers.

import React, { useEffect, useState } from "react";

export default function QueryData() {
  const [backenddata, setBackenddata] = useState([]);

  async function fetchData(url) {
    const response = await fetch(url);
    const result = await response.json()
    setBackenddata(result);
  }

  useEffect(() => {
    let url = "http://localhost:3001/"; //xampp server
    fetchData(url);
  }, []);
    
  return (
    <div>
      <img src={backenddata[0]?.ProductImage.data} />
    </div>
  );
}

Solution

The reason why the image was not showing because the encoded base64 was incorrect. You could verify your base64 result data by comparing with the data from http://jpillora.com/base64-encoder/

Initially i used this method to convert to bass64

var blob = new Blob(backenddata[0]?.ProductImage.data, {
  type: "image/jpeg",
});
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
  let base64String = reader.result;
  setImagesrc(base64String); //assigned to state. This base64 value was wrong compared to data from http://jpillora.com/base64-encoder/
};

So i have changed to below code and it was correct and same as the http://jpillora.com/base64-encoder/

  var base64String = btoa(
    String.fromCharCode(...new Uint8Array(backenddata[0]?.ProductImage.data))
  );
  setImagesrc(base64String);


Answered By - SajZ
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing