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

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

问题描述

我想将上传的文件编码为base64,以便可以将它们传递给请求.问题是我正在将Angular 2与Typescript一起使用,但找不到有关如何执行此操作的任何信息.我发现用Javascript可以用canvas完成,但是我不知道如何在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:

compontent.ts

compontent.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

component.html

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

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

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