我在尝试从刚上传的文件中获取网址时收到错误。
这一个:
未捕获的异常:[object Object]
这是我在app.component.ts中的代码:
export class AppComponent {
ref: AngularFireStorageReference;
task: AngularFireUploadTask;
uploadProgress: Observable<number>;
downloadURL: Observable<string | null>;
taskName:string;
id:string;
ngOnInit() {
}
constructor(private afStorage: AngularFireStorage){
}
upload(event) {
this.id = Math.random().toString(36).substring(2);
this.ref = this.afStorage.ref('myURL/'+this.id);
this.task = this.ref.put(event.target.files[0]);
this.uploadProgress = this.task.percentageChanges();
this.downloadURL = this.afStorage.ref('myURL/'+this.id).getDownloadURL();
}
}
这是HTML:
<div class="card">
<div class="card-header">
Firebase Cloud Storage Angular
</div>
<div class="card-body">
<h5 class="card-title">Select a file for upload</h5>
<input type="file" (change)="upload($event)" accept=".png, .jpg,"/>
<div class="progress">
<div id="progress" class="progress-bar progress-bar-striped bg-succes" role="progressbar" [style.width]="(uploadProgress | async) + '%'" [attr.aria-valuenow]="(uploadProgress | async)" aria-valuemin="0" aria-valuemax="100" ></div>
</div>
<br><br>
<div *ngIf="downloadURL | async; let downloadSrc" class="alert alert-info" role="alert">
File uploaded: <a [href]="downloadSrc">{{downloadSrc}}</a>
</div>
</div>
现在......你不需要告诉我,我意识到这是因为.getDownloadURL正在上传文件的同时执行。我知道这一点,因为当我将该功能分配给普通按钮并等待文件上传以按下它时,链接显示正常。
我遵循了一些教程,但没有一个似乎有同样的问题。
¿我怎么知道文件成功上传的时间?
非常感谢,对不起,我的英语不是很好。
答案 0 :(得分:0)
您需要做的是订阅observable task.downloadURL():
upload(event) {
this.id = Math.random().toString(36).substring(2);
this.ref = this.afStorage.ref('myURL/'+this.id);
this.task = this.ref.put(event.target.files[0]);
this.uploadProgress = this.task.percentageChanges();
this.downloadURL = this.task.downloadURL().subscribe(url => {
console.log('Your url is ready to use:', url);
});
}
答案 1 :(得分:0)
upload(event) {
const task = this.afStorage.upload('myURL/'+this.id,event.target.files[0]);
this.uploadProgress = task.percentageChanges();
this.downloadURL = task.downloadURL().subscribe(url => {
console.log('Your url is ready to use:', url);
});
}
答案 2 :(得分:0)
感谢Rahul和Mauricio的帮助,我找到了解决问题的方法:
const task = this.afStorage.upload('myURL/'+this.id,event.target.files[0]);
task.downloadURL().subscribe(url => {
this.downloadURL = this.afStorage.ref('myURL/'+this.id).getDownloadURL();
});
首先询问任务的URL是否可用,然后声明downloadURL。