angular - Angular 6 - 上传后获取 Firebase 存储文件的下载 URL
问题描述
我在这里想要完成的是一个简单的想法。
将文件上传到 Firebase 存储
获取文件的链接并将其插入表单中。
问题是,我无法获取下载 URL。
当我上传某些东西时,它确实会上传,但我收到以下错误消息:
Object { code_: "storage/object-not-found", message_: "Firebase Storage: Object 'rnmgm3vvpz' does not exist.", serverResponse_: "{\n \"error\": {\n \"code\": 404,\n \"message\": \"Not Found. Could not get object\"\n }\n}", name_: "FirebaseError" }
这是要在 component.ts 上上传的代码:
upload(event) {
const id = Math.random().toString(36).substring(2);
this.ref = this.afStorage.ref(id);
this.task = this.ref.put(event.target.files[0]);
this.uploadState = this.task.snapshotChanges().pipe(map(s => s.state));
this.uploadProgress = this.task.percentageChanges();
this.downloadURL = this.ref.getDownloadURL();
}
在 component.html 上:
<input type="file" (change)="upload($event)" accept=".png,.jpg" />
文件上传后如何获取downloadURL?
解决方案
您应该将 finalize() 添加到管道中,例如:
this.task.snapshotChanges().pipe(
finalize(() => {
this.downloadURL = this.ref.getDownloadURL(); // <-- Here the downloadURL is available.
})
).subscribe();
在 finalize() 步骤中,downloadURL 可用,因此您可以从 ref 中异步获取他。
--UPDATE
您说您使用的是 Angular 6,所以我假设您使用的是最新版本的 firebase。
他们将 getDownloadURL() 从 Task 更改为 Observable,因此要获取实际的 URL,您只需订阅即可。
this.task.snapshotChanges().pipe(
finalize(() => {
this.ref.getDownloadURL().subscribe(url => {
console.log(url); // <-- do what ever you want with the url..
});
})
).subscribe();
推荐阅读
- .net - 不再能够在我的 .NET Core3 WPF 表单上打开设计器
- python - 自定义损失函数大大减慢了多 GPU 模型的训练
- javascript - 在没有服务器访问的情况下确定您可以使用哪个 url 访问网站
- filter - 如何从 Pypsark 中的 RDD 中过滤
- python - pandas groupby:我可以通过 MultiIndex 列的一级选择 agg 函数吗?
- rust - 使用 rusoto 流式上传到 s3
- python - 将 --port 参数发送到 python
- javascript - 即使我使用 javascript 传递字符串,为什么会弹出“string.matchall 不是函数”错误?
- javascript - 页面刷新后 JSON 本地存储未保存
- php - 通过两个值获取进度