【问题标题】:How to upload an image coming from the Ionic's Camera to firebase?如何将来自 Ionic 相机的图像上传到 Firebase?
【发布时间】:2021-05-14 12:14:48
【问题描述】:

我已经设法使用 Ionic 相机 API 拍照:

  async pickImage(sourceType: CameraSource) {
    const image = await Camera.getPhoto({
      quality: 90,
      allowEditing: true,
      resultType: CameraResultType.Uri,
      source: sourceType,
    });
    console.log(image);
  }

这给了我这个:

我还发现要使用 angular fire storage 上传,但我不知道如何将两者连接起来。我真的不明白两者之间的格式是什么,我应该向 Camera API 询问什么格式以及我应该向 AngularFireStorage API 提供什么格式。

我试过这个:

const filePath = 'name-your-file-path-here';
const ref = this.storage.ref(filePath);
const task = ref.put(image.webPath);
task
  .snapshotChanges()
  .pipe(finalize(() => console.log(ref.getDownloadURL())))
  .subscribe();

但我收到此错误:

ERROR Error: Uncaught (in promise): FirebaseStorageError: {"code_":"storage/invalid-argument","message_":"Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.","serverResponse_":null,"name_":"FirebaseError"}

您的灯将不胜感激:)

【问题讨论】:

  • 我希望有人有足够的耐心给你写样板。我的评论是——一般来说你不要求格式。它返回返回的内容。 Camera.getPhoto({ 显然会返回一个 Promise,如果需要,您可以将其转换为 Observable。与 Firebase 相同 - 无论是 Promise 还是 Observable,它们都可以相互转换
  • @Bitman 是的,但是 Camera.getPhoto 获取格式(DATA_URL、FILE_URI 或 NATIVE_URI),然后承诺返回不同的值。 AngularFireStorage 也是一样,接受不同的值。我知道可观察的。如果您检查我提供的代码,它会在 observable 上awaits,但我不知道如何将此对象转换为 angularFireAuth 接受的对象。所以不,这个问题与 Promise/Observable/async 无关。
  • 嗯,确实如此。因为你 await'ing ,所以你得到的是一个已解决的 Promise 结果。如果没有 asyncawait,你可以将这个 Promise 转换为 Observable
  • 完全正确,但我仍然不明白知道如何将 promise 转换为 observable 如何帮助我知道我应该向Camera.getPhoto 询问哪种格式,调用 angularFireStorage 的哪种方法,以及我应该做什么转换。
  • 我记得 angularfire 使用 Observables,而原生 firebase 使用 Promises。如果你使用angularfire,显然使用 Observables 可能会更容易。但是,这就是我能提供的全部帮助。希望有人能沿着这条路追踪你,因为有很多东西要理解。我建议分享您的尝试,以便其他人更容易提供帮助

标签: angular firebase ionic-framework angularfire ionic-native


【解决方案1】:

“webpath”不是文件或 blob,您需要在调用 put 之前对其进行转换。 ionic网站上有一个如何转换的例子

https://ionicframework.com/docs/angular/your-first-app/3-saving-photos

private async readAsBase64(cameraPhoto: CameraPhoto) {
  // Fetch the photo, read as a blob, then convert to base64 format
  const response = await fetch(cameraPhoto.webPath!);
  const blob = await response.blob();

  return await this.convertBlobToBase64(blob) as string;  
}

convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
  const reader = new FileReader;
  reader.onerror = reject;
  reader.onload = () => {
      resolve(reader.result);
  };
  reader.readAsDataURL(blob);
});

【讨论】:

  • 谢谢,在寻找解决方案时,我已经多次看到您的名字了 :)。但是有没有办法不将其转换为 base64 字符串?我在多个地方读到这是一项相当昂贵的操作,从技术上讲,我不明白为什么在发送 blob 之前需要转换为 base64 ?
  • 获得 blob 后,可以将其传递给 firebase 并上传...不必使用字符串
  • 检查我的代码,这是我试图做的,但我得到一个错误。
猜你喜欢
  • 2018-03-09
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 2021-08-20
  • 2016-12-03
  • 2015-09-24
  • 2018-11-10
相关资源
最近更新 更多