sabertooth
sabertooth

Reputation: 620

How to convert a String to actual file that was generated from FileReader.readAsDataURL()

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()

Upvotes: 1

Views: 2405

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

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"});

Upvotes: 2

Related Questions