【问题标题】:Upload images to firebase from ReactNative从 React Native 将图像上传到 firebase
【发布时间】:2018-01-14 18:08:37
【问题描述】:

我是 firebase 新手,在将图片上传到 firebase.storage 时遇到了一点问题。

在我的应用中,我有一张图片,当我 console.log 时,我得到了这个:

file:///Users/waltermonecke/Library/Developer/CoreSimulator/Devices/B38A76A…6E2-5EE0F4B38878/Documents/images/F6DFDD32-A741-446B-B035-F8407197421C.jpg

所以基本上是对.jpg 图像的引用。现在我想上传它,这是我迄今为止的代码:

let img = job.photo1.uri;
console.log(img) // See above

let storageRef = firebase.storage().ref(`/jobs/${currentUser.uid}`);
storageRef.put(img);

我认为这已经足够了,但自从收到此错误消息后,我显然遗漏了一些东西:

Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.

非常感谢您的任何帮助。

【问题讨论】:

    标签: javascript firebase react-native firebase-storage


    【解决方案1】:

    storageRef.put 接受 Blob 而不是字符串。 React Native 没有内置方法将图像文件转换为 Blob ,因此您可以使用 react-native-fetch-blob 库来实现。

     Blob.build(img, {
          type: "image/png;"
     }).then(blob => {
         firebase
         .storage()
         .ref(`/jobs/${currentUser.uid}`)
         .put(blob, { contentType: "image/png" })
         .then(snapshot => {
             // Done upload
             blob.close();
         });
    

    【讨论】:

    • 感谢您的回答,但我没有在 Blob 对象中看到.build 方法。
    【解决方案2】:

    取决于您用于 Firebase 集成的库...假设 react-native-firebase,这应该可以工作:

    firebase
     .storage()
     .ref(`/jobs/${currentUser.uid}`)
     .putFile(img)
     .on(
       'state_changed',
       (snapshot) => {
         console.log(snapshot);
       },
       err => {
         console.error(err)
       },
       (uploadedFile) => {
         console.log(uploadedFile)
       }
     );
    

    【讨论】:

    • 我正在使用firebase,我尝试了putFile方法。但是,它似乎不是有效的方法调用。 _firebase2.default.storage(...).ref(...).putFile is not a function
    • 你在用这个包吗? github.com/invertase/react-native-firebase 那是我最初引用的那个......我知道这不是一个完整的答案,但我已经轻松使用它了。
    猜你喜欢
    • 2022-10-18
    • 2021-09-28
    • 2020-03-06
    • 2017-07-02
    • 2020-06-21
    • 1970-01-01
    • 2023-03-31
    • 2021-06-07
    • 1970-01-01
    相关资源
    最近更新 更多