以角度 5 上传前的图像预览 [英] Image preview before upload in angular 5

查看:22
本文介绍了以角度 5 上传前的图像预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码可以在上传之前显示图像预览.但是我正在使用 Angular 5,所以我有一个 .ts 文件而不是 .js 文件.我如何在 Angular 5 中做同样的事情?我还想在所有浏览器中显示图像.

I have this code to show the image preview before uploading it. However I am working with Angular 5 so I have a .ts file instead of a .js one. How can I do the same in Angular 5? I also want to show the image in all browsers.

我的 HTML:

<input type='file' onchange="readURL(this);"/>
<img id="blah" src="http://placehold.it/180" alt="your image"/>

我的 CSS:

img {
    max-width:180px;
}

input[type=file] {
    padding: 10px;
    background: #2d2d2d;
}

我的 JavaScript:

My JavaScript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('blah').src=e.target.result
        };
        reader.readAsDataURL(input.files[0]);
    }
}

推荐答案

.html

更新输入的事件属性和处理程序参数.并且您应该对 src 属性使用数据绑定.如果 src 不是 null 或未定义或硬编码的 url ('http://placehold.it/180')

Update event attr and handler param for input. And you should use data binding for src attribute. Following will apply src if it's not null or undefined or hardcoded url ('http://placehold.it/180')

<input type='file' (change)="readURL($event);" />
<img id="blah" [src]="imageSrc || 'http://placehold.it/180'" alt="your image" />

.ts

在组件 ts 文件(类)中,您应该具有在视图(html)中使用的属性 imageSrc 并且您的函数应该是该类的方法

In component ts file (class) you should have property imageSrc which be used in view (html) and your function should be a method of that class

...
imageSrc: string;
...
constructor(...) {...}
...
readURL(event: Event): void {
    if (event.target.files && event.target.files[0]) {
        const file = event.target.files[0];

        const reader = new FileReader();
        reader.onload = e => this.imageSrc = reader.result;

        reader.readAsDataURL(file);
    }
}

这篇关于以角度 5 上传前的图像预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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