Angular,文件未上传到Firebase存储

时间:2017-12-20 06:09:45

标签: html angular typescript firebase-storage angularfire2

我正在尝试创建一个上传功能,用于将文件/图像上传到我的firebase数据库存储。我已在environment.ts中粘贴了正确的API密钥,并将其导入app.module.ts,如AngularFireModule.initializeApp(environment.firebaseConfiguration, 'app-root')。我分别制作了推字符串属性功能和上传文件功能。名称和描述等其他属性被正确地推送到我的Firebase实时数据库,但文件没有上传到存储,所以我也无法获取网址。

//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>

任何人都可以帮我解决这个问题吗?请告诉我更多需要的片段。提前谢谢。

0 个答案:

没有答案