Angular2 - 显示图像 [英] Angular2 - Display image

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

问题描述

我创建了一个允许用户上传图片的Angular2应用。我想实现一个预览选项。但是,当我试图破坏它时,图像不会显示出来。我如何实现此功能?

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?

UploadComponent.ts

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

Upload.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"> 


推荐答案

你尝试的方式,你没有得到带有 fileInput.target.files [0] 的图片网址,但是一个对象。

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

获取图片网址,你可以使用 FileReader 此处的文档

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

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]);
}

这篇关于Angular2 - 显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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