1

I am trying to use Base64 encoded images in my react app.

currently I load images from a folder and looks something like this:

<img className="..." src={imageFile}></img> 

I want to use base64 encoded images, I think I can do this:

<img className="..." src={"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH...."}></img> 

the problem is that the base64 strings are huge, and for some reason I cant store them in my component. I tried putting them in a txt file and doing:

fs.readFile('image.txt', function(err, data){console.log(data);}) 

but I get tons of errors, including:

Uncaught TypeError: fs.readFile is not a function 

among others.

any ideas how to store base64 strings in a separate file and load them into my component?

Thanks!

4
  • You can not read any files in react using fs module, there is one way to do that but its bit debatable Commented Feb 28, 2022 at 17:01
  • do you know a way to store base64 strings in a separate file and then import them? Commented Feb 28, 2022 at 17:12
  • This is a very strange way to go about showing images, why not host them on your app server and have a url link to them? Commented Feb 28, 2022 at 17:48
  • true, I'm trying to deploy to Arweave, and this (I think) the easiest way to include images Commented Feb 28, 2022 at 17:58

3 Answers 3

2

You can use a variable to store base64 data and export it.

// filename.js const image = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH...."; export default image; // import import image from 'filename'; 
Sign up to request clarification or add additional context in comments.

Comments

1

There is three-way to do that, with FileReader and with fetch and the simplest way is to import it.

With Import

import Base64JSON from "./readme.json"; console.log(Base64JSON); 

With FileReader

const readFile = async (json) => new Promise((resolve, reject) => { const reader = new FileReader(); const blob = new Blob([JSON.stringify(json)]); reader.onload = async (e) => resolve(JSON.parse(e.target.result)); reader.readAsText(blob); }); 

With Fetch

const readFileUsingHttp = async (path) => { const json = await fetch(path); return json.json(); }; 

Here is the sandbox URL that shows all techniques.

Codesandbox: https://codesandbox.io/s/eager-golick-uvtcnh?file=/src/App.js

1 Comment

this is the solution! thank you, I didnt even need to use fetch or Filereader, I just had to put it in a json file and import it!
0

Decode the base64 using Buffer

let [imgSrc,setImgSrc] = useState('') // let base64_to_imgsrc = Buffer.from(base64String, "base64").toString() //add the string to the state setImgSrc(base64_to_imgsrc) 

and use it like this

 <img src={"data:image/jpeg;base64," + imgSrc} /> 

1 Comment

thanks for the reply, my main problem is storing the base64 strings. is there a way to import the strings from a txt file?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.