1

I have generated a string of a file using this:

const reader = new window.FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
  var x = reader.result.toString();
  console.log("File String :: ", x);
};

How to convert this string to actual file like if the previous file was a PDF then this string will converted to a pdf file

reader.result.toString() gives me a string like this "data:application/pdf;base64,JVBERi0xLjQKJSDi48/..........."

I want to convert it back to pdf

FileReader.readAsDataURL()

sabertooth
  • 582
  • 1
  • 7
  • 23
  • 2
    What do you mean by "the actual file"? Or more importantly, what is the problem you are trying to solve? – Taplar Nov 29 '19 at 20:35
  • 1
    I Want to convert this string to the main file format. Like if the file was in pdf then converting it back to a pdf file – sabertooth Nov 29 '19 at 20:51
  • 2
    https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript/247261#247261 The api for `readAsDataURL` references that the result of the method will be the contents of the file in base64. So it appears what you are asking is how to convert back from base64. – Taplar Nov 29 '19 at 20:54
  • 1
    Like after converting it to string it gives me a string like this : ```data:application/pdf;base64,JVBERi0xLjQKJSDi48/...........``` I want to convert it back to pdf – sabertooth Nov 29 '19 at 20:54
  • 2
    This is not a duplicate, while the [marked question](http://stackoverflow.com/questions/246801) deals with encoding/decoding base64 strings it does not answer op's question of how to get a file object from it. – Patrick Evans Nov 29 '19 at 21:20

1 Answers1

2

If you have a base64 string use atob to decode it and then use the Blob() constructor to get a Blob object (super constructor to File)

//strip off the data uri prefix
let encodedString = dataUrlString.replace('data:application/pdf;base64,','')
let data = atob(encodedString);
let blob = new Blob([data],{'type':'optional mime type here'});

//if you need a literal File object
let file = new File(blob,"filename.pdf",{type:"optional mime type"});
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87