Firebase.storage:从React表单

时间:2017-07-31 14:12:10

标签: javascript reactjs firebase firebase-storage

我正在尝试上传到Firebase存储中的一些文件,之前在React表单的输入元素中选择了

它是一个处理程序:将文件对象传递给上传器并等待(我想这样做)从它返回。

// comes from input-type element, contains icon picture 
handleIconFile =(e) => {
const iconFile = e.target.files[0]

// try to upload in order to get download url
  const downloadURL = uploadFile(iconFile, ()=>{

  // takes some time ...
  console.log(downloadURL);

  // store url to state
  this.setState({ downloadURL })
  })
}

它的上传者:它来自firebase文档并在成功处理程序中添加了return语句

/** takes File Object to upload to storage
    returns url for download this file from firebase */
uploadFile = (iconFile) => {

    // root reference
    const fileName = iconFile.name
    console.log(fileName);
    // const metadata = { contentType: 'image/jpeg' }
    const storageRef = storage.ref()
    const uploadTask = storageRef.child('/icon/'+ fileName).put(iconFile)

    // Register three observers:
    // 1. 'state_changed' observer, called any time the state changes
    // 2. Error observer, called on failure
    // 3. Completion observer, called on successful completion
    uploadTask.on('state_changed', function(snapshot){
      // Observe state change events such as progress, pause, and resume
      // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
      var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
    }, function(error) {
      // Handle unsuccessful uploads
      console.log('error:', error);
    }, function() {
      // Handle successful uploads on complete
      var downloadURL = uploadTask.snapshot.downloadURL;
      // console.log(downloadURL);
      return downloadURL // <--- I did add this myself in order to return it back to handler
    });
} 

文件已成功加载。在控制台中,我看到:Upload is 0% done Upload is 100% done

问题是:downloadURL不返回处理程序。 我可以在上传者的成功部分看到它 - // console.log(downloadURL);,但在其他任何地方都看不到它。

1 个答案:

答案 0 :(得分:2)

看起来你正试图用callback做这件事,试试这样的事情 -

handleIconFile =(e) => {
  const iconFile = e.target.files[0]

  uploadFile(iconFile, result => {

    if (result.progress) {
      // Handle progress
      return;
    }

    if (result.downloadURL) {
      this.setState({ result.downloadURL });
      return;
    }

    if (result.error) {
      // Handle error
    }
  });
}

uploadFile = (iconFile, callback) => {

  const fileName = iconFile.name
  const storageRef = storage.ref()
  const uploadTask = storageRef.child('/icon/'+ fileName).put(iconFile)

  uploadTask.on('state_changed', snapshot => {
    var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    callback({ progress });
  }, error => {
    callback({ error });
  }, () => {
    var downloadURL = uploadTask.snapshot.downloadURL;
    callback({ downloadURL });
  });
}