我正在尝试使用上传功能将文件/图像上传到我的Firebase数据库存储。 我已经将正确的API密钥粘贴到environment.ts
并将其导入到app.module.ts
例如AngularFireModule.initializeApp(environment.firebaseConfiguration, 'app-root')
。 我分别制作了推字符串属性函数和上传文件函数。 其他属性(例如名称和描述)已正确推送到我的Firebase实时数据库中,但文件未上传到存储中,因此我也无法获取该url。
//product.ts export class Product { $prdKey: string; prdName: string; prdImage ? : File; imageURL ? : any; prdDescription: string; constructor(prdImage: File) { this.prdImage = prdImage; } }
//product.service.ts Product: any; selectedProduct: Product = new Product(this.Product); currentFileUpload: Product; insertProduct(Product: Product) { this.productList.push({ prdName: Product.prdName, prdDescription: Product.prdDescription }); } private basePath = '/'; pushFileToStorage(Product: Product) { const storageRef = firebase.storage().ref(); const uploadTask = storageRef.child(`${this.basePath}/${Product.prdImage.name}`).put(Product.prdImage); uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => { // in progress const snap = snapshot as firebase.storage.UploadTaskSnapshot }, (error) => { // fail console.log(error) }, () => { // success Product.imageURL = uploadTask.snapshot.downloadURL Product.prdName = Product.prdImage.name this.saveFileData(Product) } ); } private saveFileData(Product: Product) { this.firebase.list(`${this.basePath}/`).push(Product); }
//product.component.ts onSubmit(form: NgForm) { if (form.value.$prdKey == null) { this.ProductService.insertProduct(this.ProductService.selectedProduct); } else { this.ProductService.updateProduct(this.ProductService.selectedProduct); } } upload() { const file = this.ProductService.selectedProduct.prdImage this.ProductService.currentFileUpload = new Product(file); } selectFile(event) { this.ProductService.selectedProduct = event.target.files; }
<!--product.component.html--> <form #productForm="ngForm" (ngSubmit)="onSubmit(productForm); upload()"> <!--skip name and descrioption input--> <label>Upload an Image</label> <input type="file" class="form-control"> <button type="submit" class="btn btn-primary">Submit</button> </form>
谁能帮我解决这个问题? 请让我知道需要更多片段。 先感谢您。