有人能指导我同时上传多张图片到Firebase吗?
我要做的是将几个图像上传到Firebase存储,并将每个引用保存在Firestore中(例如,在一个数组中)。我已经设法做到了,但只有一个形象。我正在使用Angularfire存储。
https://stackblitz.com/edit/upload-multiple-firebase
目前情况如下:
在存储中看起来是这样的(请注意,图像位于具有相同Firestore ID的文件夹中):
这是我的密码:
组件.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { AngularFireStorage } from 'angularfire2/storage';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FirebaseService } from './services/firebase.service';
export interface Test {
imagenDestacada: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
uploadPercent: Observable<number>;
downloadURL: Observable<string>;
selectedFile: FileList | null;
forma: FormGroup;
tests: Observable<any[]>;
constructor(fb: FormBuilder, private storage: AngularFireStorage, private afs: AngularFirestore, private fs: FirebaseService ) {
this.forma = fb.group ({
categoria: ['myCategoria'],
})
}
ngOnInit() {
this.mostrarImagenes();
}
detectFiles(event) {
this.selectedFile = event.target.files[0];
}
uploadFile() {
const myTest = this.afs.collection('test').ref.doc();
console.log(myTest.id)
const file = this.selectedFile
const filePath = `${myTest.id}/name1`;
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file);
this.uploadPercent = task.percentageChanges();
task.snapshotChanges().pipe(
finalize(() => {
fileRef.getDownloadURL().toPromise().then( (url) => {
this.downloadURL = url;
myTest.set({
categoria: this.forma.value.categoria,
imagenes : this.downloadURL,
myId : myTest.id
})
console.log( this.downloadURL )
}).catch(err=> { console.log(err) });
})
)
.subscribe()
}
mostrarImagenes() {
this.tests = this.fs.getTests();
}
}
<div class="container py-4">
<input type="file" multiple (change)="detectFiles($event)">
<button (click)="uploadFile()" class="btn btn-primary">UPLOAD</button>
<div>{{ uploadPercent | async }}</div>
<a [href]="downloadURL">{{ downloadURL }}</a>
<hr>
<div class="row">
<div class="col-lg-2 col-6" *ngFor="let test of tests | async">
<div class="card">
<img class="card-img-top" src="{{ test.imagenes }}" width="100%">
<div class="card-body">
<p class="card-text">My text</p>
</div>
</div>
</div>
</div>
</div>
服务.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
@Injectable()
export class FirebaseService {
tests: Observable<any[]>;
constructor( private afs: AngularFirestore ) { }
getTests() {
this.tests = this.afs.collection('test').valueChanges();
return this.tests;
}
}