typescript Angular2 - 显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39933340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:55:13  来源:igfitidea点击:

Angular2 - Display image

imageangulartypescript

提问by AJ_

I created a Angular2 app that allows the user to upload images. I want to implement a preview option. However, when i try to imperilment it the image doesn't show up. How do i achieve this feature?

我创建了一个 Angular2 应用程序,允许用户上传图像。我想实现一个预览选项。然而,当我试图危害它时,图像没有出现。我如何实现此功能?

UploadComponent.ts

上传组件.ts

import * as ng from '@angular/core';
//import { UPLOAD_DIRECTIVES } from 'ng2-uploader';
import {UploadService} from '../services/upload.service'; 

@ng.Component({
  selector: 'my-upload',
  providers:[UploadService], 
  template: require('./upload.html')
})
export class UploadComponent {
    progress:any; 
    logo:any; 
    filesToUpload: Array<File>;
    constructor(public us:UploadService){
        this.filesToUpload = [];
    }
    upload() {
        this.us.makeFileRequest("http://localhost:5000/api/SampleData/Upload", this.filesToUpload)
        .then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }
    onFileChange(fileInput: any){
        this.logo = fileInput.target.files[0];
    }
}

Upload.html

上传.html

<h2>Upload</h2>
<input type="file" (change)="onFileChange($event)" placeholder="Upload image..." />
<button type="button" (click)="upload()">Upload</button>
 <img [src]="logo" alt="Preivew"> 

回答by Alexandru Pufan

The way you try it, you don't get the image URL with fileInput.target.files[0], but an object.

按照您尝试的方式,您得到的不是带有 的图像 URL fileInput.target.files[0],而是一个对象。

To get an image URL, you can use FileReader(documentation here)

要获取图像 URL,您可以使用FileReader此处的文档

onFileChange(fileInput: any){
    this.logo = fileInput.target.files[0];

    let reader = new FileReader();

    reader.onload = (e: any) => {
        this.logo = e.target.result;
    }

    reader.readAsDataURL(fileInput.target.files[0]);
}

回答by arul prince

  
  filesToUpload: Array<File> = [];
  url: any;
  image: any;
  
//file change event 
  
  filechange(fileInput: any) {

    this.filesToUpload = <Array<File>>fileInput.target.files;
    this.image = fileInput.target.files[0]['name'];
    this.readurl_file(event);
  }
  
//read url of the file
  
  readurl_file(event) {
    if (event.target.files && event.target.files[0]) {
      const reader = new FileReader();
      reader.onload = (eve: any) => {
        this.url = eve.target.result;
      };
      reader.readAsDataURL(event.target.files[0]);
    }
  }
  
   
   <div  class="form-group">
      <label for="image">Image</label>
      <input type="file"  class="form-control"  (change)="filechange($event)" placeholder="Upload file..." >
    </div>
    <div class="container">
        <img [src]="url">
    </div>
  
  

回答by markkan

Using FileReader is not a good practice. If an image is too large it can crash your browser because onload function load whole image in RAM.

使用 FileReader 不是一个好习惯。如果图像太大,它可能会导致浏览器崩溃,因为 onload 函数将整个图像加载到 RAM 中。

Better approach is to use:

更好的方法是使用:

url = URL.createObjectURL($event.target.files[0]);

Then, show it out with DomSanitizer:

然后,用 DomSanitizer 展示它:

this.sanitizer.bypassSecurityTrustUrl(url)

So in ts:

所以在 ts 中:

constructor(private sanitizer: DomSanitizer) {} 

onFileChange(fileInput: any){
    this.url = URL.createObjectURL($event.target.files[0]);
}

get previewUrl(): SafeUrl {
   return this.sanitizer.bypassSecurityTrustUrl(this.url);
}

And in html:

在 html 中:

<img [src]="previewUrl"/>