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

5
  • 2
    What do you mean by "the actual file"? Or more importantly, what is the problem you are trying to solve? Commented Nov 29, 2019 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 Commented Nov 29, 2019 at 20:51
  • 2
    stackoverflow.com/questions/246801/… 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. Commented Nov 29, 2019 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 Commented Nov 29, 2019 at 20:54
  • 2
    This is not a duplicate, while the marked question deals with encoding/decoding base64 strings it does not answer op's question of how to get a file object from it. Commented Nov 29, 2019 at 21:20

1 Answer 1

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"});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.