Mri*_*Pal 6 file-upload path angular
html的
<input type='file' onchange="readURL(this);" />
<img id="blah" src="http://placehold.it/180" alt="your image" />
Run Code Online (Sandbox Code Playgroud)
的CSS
img{
max-width:180px;
}
input[type=file]{
padding:10px;
background:#2d2d2d;}
Run Code Online (Sandbox Code Playgroud)
.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]);
}
}
Run Code Online (Sandbox Code Playgroud)
我有这个代码在上传之前显示图像预览.但是我正在使用angular 5,所以我有.ts文件而不是.js.如何在角度5中执行相同操作.我还想在所有浏览器中显示图像.请帮忙.提前致谢.
Cof*_*Tea 28
html的
更新事件attr和处理程序参数以进行输入.你应该使用数据绑定src属性.如果src不为null或未定义或硬编码url(' http://placehold.it/180 '),则以下将应用src
<input type='file' (change)="readURL($event);" />
<img id="blah" [src]="imageSrc || 'http://placehold.it/180'" alt="your image" />
Run Code Online (Sandbox Code Playgroud)
.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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用以下代码来实现图像预览:
onFileChange(event: any) {
this.userFile = event.target.files[0];
this.imageSelected = this.userFile.name;
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e: any) => {
this.imageSrc = e.target.result;
};
reader.readAsDataURL(event.target.files[0]);
}}
Run Code Online (Sandbox Code Playgroud)
这工作得很好并显示图像预览。我最初面临的问题是,每次生成图像预览时,我都会在 chrome 开发人员工具中收到以下错误:
不过一切正常,没有其他错误。
如果我点击 null:1 我被定向到以下内容:
经过一些摆弄和故障排除后,我能够找到我在下面的编辑中包含的解决方案。
编辑:想通了。我没有 || ' http://placehold.it/180 '" 包含在我的 component.html 上的 [src]=" 中。猜测是时间问题。现在排序。没有更多的错误。
我知道我迟到了,但只是在图像和音频方面遇到了这个问题。上述解决方案适用于图像,但不适用于音频。我最终通过使用 URL 对象而不是每个人都在使用的 FileReader 对象来完成所有工作。类似于以下内容
component.ts 文件~
imgSrc = 'assets/path/to/default/image.jpeg'
imgFileSelected(event: any) {
if (event.target.files && event.target.files[0]) {
this.imgSrc = URL.createObjectURL(event.target.files[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
我的component.html看起来像~
<img [src]="imgSrc | sanitizeUrl"> <!-- using a Custom Pipe -->
Run Code Online (Sandbox Code Playgroud)
最后,我创建了一个自定义管道来消除警告控制台。我的管子如下~
@Pipe({
name: 'sanitizerUrl'
})
export class SanitizerUrlPipe implements PipeTransform {
constructor (
private sanitize: DomSanitizer
) {}
transform(value: string): SafeUrl {
return this.sanitize.bypassSecurityTrustUrl(value);
}
}
Run Code Online (Sandbox Code Playgroud)
要了解我如何将其用于音频标签,您可以查看此链接。 它只有 2 行不言自明的代码。
| 归档时间: |
|
| 查看次数: |
24435 次 |
| 最近记录: |