Angular 2 将图像编码为 base64 [英] Angular 2 encode image to base64

查看:50
本文介绍了Angular 2 将图像编码为 base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将上传的文件编码为 base64,以便将它们传递给请求.问题是我正在使用带有 Typescript 的 Angular 2,但我找不到任何关于如何做到这一点的信息.我发现在 Javascript 中可以用画布完成,但我不知道如何在 Typescript 中实现代码.

I want to encode the uploaded files to base64 so that I can pass them to the request. The problem is that I'm using Angular 2 with Typescript and I couldn't find any info on how to do that. I found that in Javascript it can be done with canvas but I don't know how could I implement the code in Typescript.

<input type="file" class="form-control" accept="image/*" multiple
    [(ngModel)]="spot.images" name="images">

推荐答案

于是我找到了解决方案:

So I find the solution:

组件.ts

changeListener($event) : void {
  this.readThis($event.target);
}

readThis(inputValue: any): void {
  var file:File = inputValue.files[0];
  var myReader:FileReader = new FileReader();

  myReader.onloadend = (e) => {
    this.image = myReader.result;
  }
  myReader.readAsDataURL(file);
}

component.html

<input type="file" accept="image/*" (change)="changeListener($event)">

这篇关于Angular 2 将图像编码为 base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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