Angular 将pdf URL转换为Base64

Angular 将pdf URL转换为Base64,angular,pdf,base64,Angular,Pdf,Base64,在我的angular应用程序中,我使用以下代码将任何文件转换为Base64字符串 handleUpload(event) { const file = event.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { console.log(reader.result); }; } 在

在我的angular应用程序中,我使用以下代码将任何文件转换为Base64字符串

handleUpload(event) {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
        console.log(reader.result);
    };
}
在这里,我想动态地将pdf URL转换为base64。这是我想要转换base64的示例URL


您可以使用
HttpClient
从url获取文件。首先,您必须在
app.module.ts

import { HttpClientModule } from '@angular/common/http';
imports: [...,
     'HttpClientModule',
       ...]
然后从
'@angular/common/http'
导入component.ts
HttpClient
,并在构造函数中添加实例

constructor(private http: HttpClient) { }
添加方法

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