0

I have a base64 of a .txt file and I want to display it in React. The file looks like this:

ID:948201
name:"someText"
description:".txt"
base64File:"QU5URSBQVVBBQ0lDIEtSQUFBQUFBQUFBQUFMSg=="

Can I display the text of the document, which is "ANTE PUPACIC KRAAAAAAAAAAALJ", somehow on the browser?

OmarLittle
  • 423
  • 1
  • 9
  • 18

3 Answers3

2

you can decode base64 using atob():

<div id="text"></div>

<script>
  let data = {
    "ID":948201,
    "name":"someText",
    "description":".txt",
    "base64File":"QU5URSBQVVBBQ0lDIEtSQUFBQUFBQUFBQUFMSg=="
  }

  let decodedText = atob(data.base64File);
  document.getElementById("text").innerText = decodedText;
</script>
Emanuel Trandafir
  • 1,526
  • 1
  • 5
  • 13
1

Yes, you can turn the base64 to a File and then use FileReader API to read the File as a text.

function dataURLtoFile(dataurl, filename) {

  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  return new File([u8arr], filename, {
    type: mime
  });
}


//Usage example:
var file = dataURLtoFile('data:text/plain;base64,QU5URSBQVVBBQ0lDIEtSQUFBQUFBQUFBQUFMSg==', 'hello.txt');
var fr = new FileReader();
fr.readAsText(file);
fr.onload = function() {
  console.log(fr.result);
};

References.

Turn base64 to file

Use FileReader API to read the file text.

Mina
  • 14,386
  • 3
  • 13
  • 26
  • I like your solution, but how do I display it in react with jsx? Using div, input? – OmarLittle Mar 08 '23 at 10:12
  • @OmarLittle Thanks, if you want to display the text, then create a `state` for that text, and then the `setState` once you parse the file, and show the `state` in the UI. – Mina Mar 08 '23 at 11:35
0

I have no idea in which format you may want to convert your file, I hope following link may help you : https://forums.meteor.com/t/base64-convert-back-to-file/34188

Asma
  • 103
  • 5