Angular Firebase上传图像

时间:2018-11-22 11:32:53

标签: firebase angular5 google-cloud-firestore

我是使用Angular 5和firebase的初学者。 作为实践,我决定创建一个博客。 我的问题是我无法在Firestore中上传图片。当我上传到云端存储并尝试检索下载链接时,它没有在Firestore中注册。

看看我的代码并给我建议。

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/shared/services/auth.service';
import { finalize } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { AngularFireStorage } from '@angular/fire/storage';
import { PostsService } from 'src/app/shared/services/posts.service';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';



@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {

  uploadPercent: Observable<number>;
  downloadURL: Observable<string>;

  title: string;
  content: string;
  description: string;
  image: string = null;

  constructor(private auth: AuthService,
    private toast: ToastrService,
    private postService: PostsService,
    private store: AngularFireStorage,
    private router: Router) { }

  ngOnInit() {
  }

  createPost() {
    // tslint:disable-next-line:prefer-const
    let data = {
      content: this.content,
      image: this.image,
      description: this.description,
      publication: new Date(),
      title: this.title
    };
    this.router.navigate(['/admin']);
    this.postService.create(data);
    this.title = '';
    this.description = '';
    this.content = '';
    this.toast.success('Votre article a été publié');
  }

  uploadImage(event) {
    // tslint:disable-next-line:prefer-const
    let file = event.target.files[0];
    // tslint:disable-next-line:prefer-const
    let path = `posts/${file.name}`;
    if (file.type.split('/')[0] !== 'image') {
      return alert('Erreur, ce fichier n\'est pas une image');
    } else {
      // tslint:disable-next-line:prefer-const
      let ref = this.store.ref(path);
      // tslint:disable-next-line:prefer-const
      let task = this.store.upload(path, file);
      this.uploadPercent = task.percentageChanges();
      console.log('Image chargée avec succès');
      task.snapshotChanges().pipe(
        finalize(() => {
          this.downloadURL = ref.getDownloadURL();
          this.downloadURL.subscribe(url => {
            console.log(url);
          });
        }
        )
      ).subscribe();
    }
  }

}
<div class="col-8">

        <div class="input-group mb-3">
          <div class="custom-file">
            <input type="file" class="custom-file-input" id="inputGroupFile03" aria-describedby="inputGroupFileAddon03" (change)="uploadImage($event)" accept=".png,.jpg" [(ngModel)]="image">
            <label class="custom-file-label" for="inputGroupFile03">Choisir une image</label>
          </div>
        </div>
        <div class="progress" [hidden]="!uploadPercent">
          <mat-progress-bar mode="determinate" value="{{ uploadPercent | async }}"></mat-progress-bar>
          {{ uploadPercent | async }}
        </div>
        <div [hidden]="!image">
          <img [src]="image || '//:0'">
        </div>

        <div class="form-group">
          <label for="title"> Titre du post </label>
          <input type="text" class="form-control" name="title" id="title" placeholder="Titre" required [(ngModel)]="title"/>
        </div>

        <div class="form-group">
          <label for="description"> Description </label>
          <input type="text" class="form-control" name="description" id="description" placeholder="Desciption"
            data-toggle="tooltip" data-placement="top" title="Ajouter une breve description de l'article" required [(ngModel)]="description"/>
        </div>

        <div class="form-group">
          <label for="content"> Contenu de l'artcle </label>
          <textarea class="form-control" name="content" id="content" cols="15" rows="5" placeholder="..." required [(ngModel)]="content"></textarea>
        </div>

        <button class="btn btn-success btn-lg btn-block" (click)="createPost()">Poster l'article <i class="fa fa-paper-plane"
            aria-hidden="true"></i>
        </button>

      </div>

enter image description here

0 个答案:

没有答案