Angular 7-尝试在上传之前创建音频文件的预览 [英] Angular 7 - Trying to create a preview of an audio file before upload
问题描述
我想要的结果是在将音频文件上传到服务器之前创建一个音频文件的预览.但是,在文件输入之后,什么也没有发生.没有将文件动态添加到aduio标签,也没有收到任何错误.控制台显示文件已加载.任何帮助将不胜感激!
My desired result is to create a preview of an audio file before it is uploaded to the server. However after file input, nothing happens. A file is not dynamically added to the aduio tag, nor do I receive any errors. The console shows that the file was loaded. Any help would be greatly appreciated!
我的组件html具有〜
My component html has~
<audio controls #figAudio>
<source [src]="audSrc" type="audio/ogg">
<source [src]="audSrc" type="audio/mpeg">
<source [src]="audSrc" type="audio/wav">
</audio>
<input type="file" (change)="audFileSelected($event)">
我的ts文件有〜
audSrc: SafeUrl;
constructor (
private sanitize: DomSanitizer
) {}
sanitizeUrl(url: string) {
return this.sanitize.bypassSecurityTrustUrl(url);
}
audFileSelected(event: any) {
console.log(event.target.files[0]);
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = (evt: any) => {
this.audSrc = evt.target.result;
};
}
}
推荐答案
好的,我解决了这个问题.我没有使用FileReader,而是使用URL对象.然后,我使用自定义管道清理音频URL.
Okay, I solved the issue. Instead of using FileReader I just use a URL object. I then use a custom pipe to sanitize my audio url.
component.ts文件〜
component.ts file~
@ViewChild('figAudio') figAudio: ElementRef; // audio tag reference
audSrc = 'path/to/default/sound.mpeg';
audFileSelected(event: any) {
if (event.target.files && event.target.files[0]) {
const audSrc = URL.createObjectURL(event.target.files[0]);
this.figAudio.nativeElement.src = this.audSrc;
}
}
component.html文件〜
component.html file~
<audio #figAudio>
<source [src]="audSrc | sanitizerUrl" type="audio/ogg">
<source [src]="audSrc | sanitizerUrl" type="audio/mpeg">
<source [src]="audSrc | sanitizerUrl" type="audio/wav">
</audio>
sanitize-url.pipe.ts〜
sanitize-url.pipe.ts ~
@Pipe({
name: 'sanitizerUrl'
})
export class SanitizerUrlPipe implements PipeTransform {
constructor (
private sanitize: DomSanitizer
) {}
transform(value: string): SafeUrl {
return this.sanitize.bypassSecurityTrustUrl(value);
}
}
这篇关于Angular 7-尝试在上传之前创建音频文件的预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!