javascript - 以角度 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]);
}
}
解决方案
.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);
}
}
推荐阅读
- sql - 如何在 sql 中使用 max() 查找前 5 个值
- laravel - 如何像 5.3 一样更改 laravel 5.2 的错误视图?
- glassfish - Payara 部署组未启动
- c++ - 重置升压累加器 C++
- security - 网址 URL 与实际网站不同
- arrays - 在单元格或单元格区域中将函数作为数组添加
- android - 谷歌地图集成后我的应用程序无法打开
- callback - Javascript中Callback的严格定义
- terraform - 如何在 terraform 中运行 powershell 脚本?
- amazon-web-services - 使用身份池(联合身份)时如何通过管理员创建用户