繁体   English   中英

如何对firebase存储图像URL进行软编码

[英]How to softcode firebase storage image url's

我正在使用Firebase Storage创建图像URL并将其发送到Firebase数据库。 当我同时对'currentUser'和Firebase Storage子引用进行硬编码时,我的工作效果很好。 但是,如何从Firebase数据库中获取实际的currentUser并在子引用中添加一个易记的名称? 我已经在Java中看到了一些可能的答案。 但不是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 Storage中的文件夹)。 我知道Firebase Realtime Database如何将其自己的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 Storage中针对图像子名称和'currentUser'实现此目的? 而且由于移动应用程序仅从数据库中获取网址,我是否真的需要将每个图像分配给Firebase存储中的“ currentUser”文件夹?

@parohy感谢您抽出宝贵的时间在Firebase文档中进行搜索。 我认为.once()仅适用于Firebase实时数据库。 而且我正在Firebase Storage中寻找唯一的名称。 但是,您的回答帮助我提出了解决方案。 我正在尝试利用Firebase数据库已经创建完全唯一的ID的事实。 但是,我认为我无法访问Firebase Storage中的那些。 所以我只是做了:

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

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

并非完全独特,但足够接近。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM