【问题标题】:How to softcode firebase storage image url's如何对 Firebase 存储图像 url 进行软编码
【发布时间】:2018-05-19 14:26:00
【问题描述】:

我正在使用 Firebase 存储来创建图像 url 并将其发送到 Firebase 数据库。当我同时有一个“currentUser”和一个 Firebase Storage 子引用硬编码时,我可以很好地工作。但是,我如何从 Firebase 数据库中获取实际的 currentUser 并为子引用/引用添加一个流畅的名称?我已经在 J​​ava 中看到了一些可能的答案。但不是Javascript。这是我的代码:

// openImage() is the function that grabs a photo from the camera roll
// I'm using react-native btw, so some of this code is handling the 
// blob. 

openImage() {
this.setState({ loading: true });
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

// if I use this code, it won't return the urls: const {currentUser}  
// = firebase.auth()

// So, I've got the 'currentUser' hardcoded in as "12345"

const { currentUser } = "12345"

// ImagePicker.openPicker() is just a library to access the camera roll

ImagePicker.openPicker({
  width: 400,
  height: 300,
  cropping: true,
  mediaType: 'photo',
}).then(image => {
  const imagePath = image.path;

  let uploadBlob = null;

  const storage = firebase.storage();
  const storageRef = storage.ref(currentUser);

  //I also have the .child reference name hardcoded as 'dp.jpg'       

  const imageRef = storageRef.child('dp.jpg');
  const mime = 'image/jpg';
  fs.readFile(imagePath, 'base64')
    .then((data) => {

      return Blob.build(data, { type: `${mime};BASE64` });
  })
  .then((blob) => {
      uploadBlob = blob;
      return imageRef.put(blob, { contentType: mime });
    })
    .then(() => {
      uploadBlob.close();
      return imageRef.getDownloadURL();
    })
    .then((url) => {
      const { image } = this.props;

      this.props.entryUpdate({ prop: 'image', value: url })


  });
});

}

然后将图像 url 传递到 Firebase 数据库并将其设置为“image”键和“dp.jpg”值。通过硬编码,这可以正常工作,但当然只适用于一个图像和一个用户(或 Firebase 存储中的文件夹)。我知道 Firebase 实时数据库如何将它自己的 ID 号分配给一个项目,如下所示:

const { currentUser } = firebase.auth();
const item = firebase.database().ref(`/users/${currentUser.uid}/items`)
.push();
return () => {
item.set({ make, model, year, uid: item.key, image })

其中 item.key 由 Firebase 生成,因此不必硬编码。是否可以在 Firebase 存储中为图像子名称和“当前用户”实现这一点?我真的需要将每个图像分配到 Firebase 存储中的“currentUser”文件夹,因为移动应用程序仅从数据库中获取 url?

【问题讨论】:

  • 您是否尝试将.once('value') 链接到storage.ref(currentUser) 上?或者您是否尝试过记录它返回的内容?只是假设。根据文档示例,您不应该这样做const item = firebase.storage().ref().child(currentUser) 吗?

标签: javascript react-native firebase-realtime-database firebase-storage


【解决方案1】:

@parohy 感谢您花时间搜索 firebase 文档。我认为 .once() 仅适用于 Firebase 实时数据库。我正在寻找 Firebase Storage 中的唯一名称。但是,您的回答帮助我找到了解决方案。我试图利用 Firebase 数据库已经创建完全独特的 ID 的事实。但是,我认为我无法访问 Firebase Storage 中的内容。所以我就这么做了:

firebase.storage().ref().child(unique + '.jpg') 

const unique = Date.now() + Math.random(); 

不是完全独特,但足够接近。

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 2017-08-10
    • 2011-08-29
    • 2019-03-10
    • 2019-03-07
    • 2016-09-18
    • 2015-08-22
    • 2021-10-14
    • 2020-12-18
    相关资源
    最近更新 更多