在Angle 5中上传之前的图像预览 [英] Image preview before upload in angular 5

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

问题描述

.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;}

.js

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

我有这段代码可以在上传之前显示图像预览.但是我正在使用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 .ts file instead of .js. How can I do the same in angular 5. I also want to show image in all browsers. Please help. Thanks in advance.

推荐答案

.html

更新事件属性和输入的处理程序参数. 并且您应该对src属性使用数据绑定.如果它不是null或未定义或经过硬编码的网址,则以下内容将适用src(" 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);
    }
}

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

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