簡體   English   中英

Angular 2:從文件上傳中獲取圖像

[英]Angular 2: get image from file upload

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

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

我想在我的javascript代碼中從uploaderevent對象創建一個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>

工作的plunker

您也可以使用ng2-file-upload執行此操作。 檢查以下代碼

組件代碼:

    import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
    import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
    import { FileItem } from 'ng2-file-upload';

    @Component({
       selector: 'app-image',
       templateUrl: './image.component.html',
       styleUrls : []
    })
    export class ImageComponent implements OnInit {

      public imageUrlPath: SafeUrl;
      public uploader: FileUploader;
      constructor(private sanitizer: DomSanitizer ){
           this.uploader = new FileUploader({
                allowedMimeType: [],
                maxFileSize: 10 * 1024 * 1024, // 10 MB
            });
            this.uploader.onAfterAddingFile = (fileItem) => {
                  fileItem.withCredentials = false;
                  this.imageUrlPath  = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(fileItem._file)));
             };
       }
   ngOnInit(){}    

    }

HTML代碼:

 <input type="file" ng2FileSelect [uploader]="uploader">
  <div>
   <img *ngIf="imageUrlPath" [src] = imageUrlPath>              
 </div>

點擊此鏈接: 圖像預覽圖像指令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM