Issue
In my angular application, I used the below code for convert any file to Base64 string.
handleUpload(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
console.log(reader.result);
};
}
Here, I want to convert the pdf URL to base64 on the fly. Here’s my sample URL which I want to convert base64.
https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf
Solution
You can use HttpClient
to get the file from url. First you have to import HttpClientModule
in app.module.ts
import { HttpClientModule } from '@angular/common/http';
imports: [...,
'HttpClientModule',
...]
After that import in your component.ts HttpClient
from '@angular/common/http'
and add the instance in the constructor.
constructor(private http: HttpClient) { }
add the method
convertToBase64(url: string){
this.http.get(url, { responseType: 'blob' })
.subscribe(blob => {
const reader = new FileReader();
const binaryString = reader.readAsDataURL(blob);
reader.onload = (event: any) => {
//Here you can do whatever you want with the base64 String
console.log('File in Base64: ', event.target.result);
};
reader.onerror = (event: any) => {
console.log("File could not be read: " + event.target.error.code);
};
});
}