Angular 2 : get image from file upload

标签 angular ng2-bootstrap

嗨,在我的 Angular 2 应用程序中,我正在使用 ng2-file-upload:

<input type="file" ng2FileSelect [uploader]="uploader" multiple (change)="onChange($event)">

我想在 uploaderevent 对象的 javascript 代码中创建一个 image 对象的实例。有点像:

public onChange(event) {
   let item = this.uploader.queue[0];
   let img = new Image();

   img.src = item.SOMETHING;
       OR
   img.src = event.SOMETHING;

}

我不知道该怎么做。

最佳答案

您可以在没有任何第三方库的情况下做到这一点。

helloworld.component

import {Component} from 'angular2/core';

@Component({
  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  templateUrl: 'src/hello_world.html',
  styles: [`
    .preview img{
      max-height: 50px;
    }
  `]
})
export class HelloWorld {

  // Declaring the variable for binding with initial value
  yourName: string = '';

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
      let file: File = fileList[0];
      var img = document.querySelector("#preview img");
      img.file = file;

      var reader = new FileReader();
      reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
      reader.readAsDataURL(file);
    }
  }
}

src/hello_world.html

<div id="preview" class="preview">
  <img src="">
</div>
<form>
  <input type="file" (change)="fileChange($event)" placeholder="Upload file">
</form>

Working plunker

关于 Angular 2 : get image from file upload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647824/

相关文章:

angular - 如何使用 angular2 将 appsettings.json 中的值读取到 typescript 文件?

angular - PrimeNG 订单列表更改按钮位置

javascript - 改进管脚输入组件

angular - 仅在单击外部时隐藏日期选择器

css - Angular2 根据组件选择器名称应用 css

angular - 在 Angular 2 typescript 中打开页面加载时的 ng2bootstrap 模式

angularjs - 使用 ng2-bootstrap 时没有将 "exportAs"设置为 "bs-modal"的指令

angularjs - 将 ng2-bootstrap 与 Angular 2 RC 6 一起使用 - 无法绑定(bind)到无法绑定(bind)到 [...] 因为它不是 [...] 的已知属性

javascript - 如何使用 yAxisTickFromatting 在 ngx-Charts Bar 上垂直设置百分比 yAxis?

angular - 如何在 Angular Material List 中使用 Item 组件