首页 > 解决方案 > 以角度 5 上传前的图像预览

问题描述

我有这段代码可以在上传之前显示图像预览。但是我正在使用 Angular 5,所以我有一个.ts文件而不是一个文件.js。我怎样才能在 Angular 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;
}

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

标签: javascriptangularimagefile-uploadpath

解决方案


.html

更新输入的事件属性和处理程序参数。你应该对 src 属性使用数据绑定。以下将应用 src 如果它不是 null 或未定义或硬编码的 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 文件(类)中,您应该具有imageSrc在视图(html)中使用的属性,并且您的函数应该是该类的方法

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

推荐阅读