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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.