1

i am new to angular and i want to convert files into base64 string. i try this and it gives base64 string but when i try to decode it using online tool it did not give correct result can anyone help me thank you.

can we convert pdf and word file into base64 or just images. with my code i successfully converted images but not any other file

my html code:

 <input type="file" (change)="base($event)">

and my ts code:

 base(event: { target: { files: any[]; }; }) {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
    console.log(reader.result);
};

}

  • Does this answer your question? [How can I convert an image into Base64 string using JavaScript?](https://stackoverflow.com/questions/6150289/how-can-i-convert-an-image-into-base64-string-using-javascript) – Suraj Gautam Dec 13 '20 at 17:05
  • @SurajGautam sir with the above code i successfully converted images but not text files like pdf, docs etc i want to know that we can only convert images into base64 or can we also converted pdf into base64 ?? – Abhishek Agarwal Dec 13 '20 at 17:17

1 Answers1

1

Your code works fine. Are you sure you are correctly getting the file object?

Below is the stackblitz demo of the same.

Also, it better to use promise while reading files. You can use below function to read a file. It takes file as input and resolves to base64 string.

private readBase64(file): Promise<any> {
const reader = new FileReader();
const future = new Promise((resolve, reject) => {
  reader.addEventListener('load', function () {
    resolve(reader.result);
  }, false);
  reader.addEventListener('error', function (event) {
    reject(event);
  }, false);

  reader.readAsDataURL(file);
});
return future;

}

Call this function as below -

this.readBase64(file)
    .then((data) => {
        // your code
    });
Nikhil Patil
  • 2,480
  • 1
  • 7
  • 20