如何在 Angular 7 中显示 base64 图像? [英] How do I display a base64 image in Angular 7?

查看:31
本文介绍了如何在 Angular 7 中显示 base64 图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想采用 base64 字符串并用它来显示图像.
下面是 HTML 文件.我想使用base64字符串并在img标签中使用它:

I want to take the base64 string and use it to display the image.
Below is the HTML file. I want to use the base64 string and use it in the img tag:

<ion-content>
  <ion-card>
      <img src={{imageFileBinary}} />
        <ion-card-header>
            <form>
                <ion-input id="myform" type="file" name="file" (change)="postMethod($event.target.files)"></ion-input>
            </form>
        <ion-card-title>Nick</ion-card-title>
    </ion-card>
</ion-content>

我从 .ts 文件中获取 imageFileBinary.
下面是 .ts 文件:

I get imageFileBinary from the .ts file.
Below is the .ts file:

export class MyprofilePage implements OnInit {


  imageFileBinary;

  userDetails: UserDetails;
  constructor(private profileDetailService: ProfileDetailsService, private httpClient: HttpClient) {}

  fileToUpload;

  getProfileDetails() {
    this.profileDetailService.getUserDetails('email').subscribe((userDetails: UserDetails) => {
      this.imageFileBinary = userDetails.imageFileBinary
    });
  }
  postMethod(files: FileList) {
    this.fileToUpload = files.item(0);
    let formData = new FormData();
    formData.append('file', this.fileToUpload, this.fileToUpload.name);

    this.httpClient.post("http://localhost:8080/uploadFile", formData).subscribe((val)=> {
      console.log(val);
    });
    return false;
  }
  ngOnInit() {
    this.getProfileDetails();

  }

}


How can I use the base64 String in the img tag?

推荐答案

试试这个..

使用 javascript btoa 函数将您的图像二进制数据转换为 base64 并将其附加数据 uri 属性.

Convert your image binary data to base64 using javascript btoa function and append it with data uri property.

imageUrl; //rename imageFileBinary to imageUrl

let imageBinary = userDetails.imageFileBinary; //image binary data response from api
let imageBase64String= btoa(imageBinary);
this.imageUrl = 'data:image/jpeg;base64,' + imageBase64String;

最后用angular数据绑定设置

Finally set it with angular data binding

<img src={{imageUrl}} />

这篇关于如何在 Angular 7 中显示 base64 图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆