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有~
<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 文件有 ~
My component ts file has ~
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;
};
}
}
推荐答案
好的,我解决了这个问题.我只使用 URL 对象,而不是使用 FileReader.然后我使用自定义管道来清理我的音频网址.
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屋!