正在尝试将图像上传到Firebase存储,但不断收到错误:无法读取未定义的属性'名称'

问题描述 投票:1回答:3

您好,我正在尝试将图像上传到Firebase存储器,但是在按照Firebase官方网站中的所有说明进行操作之后,我试图找出此错误:

未捕获的TypeError:无法读取未定义的属性'名称'在uploadFile(gastro.js:72)在HTMLButtonElement.onclick(gastro.html:57)

<div>
  <label class="upload-group">
    <h1>Upload file</h1>
    <input type="file" class="upload-group" id="file">
  </label>
  <button type="button" class="btn btn-primary" name="url[]" id="uploadButton" 
  onclick="uploadFile()">Submit</button>  // second error is here
</div>

var provider = new firebase.auth.GoogleAuthProvider();
var user;
var selectedFile;

function handleFileSelect(event) {
	$(".upload-group").show();
	selectedFile = event.target.files[0];
};


function uploadFile() {
  var filename = selectedFile.name; //first error is here
  var storageRef = firebase.storage().ref('/dogImages/' + filename);
  var uploadTask = storageRef.put(selectedFile);

    // 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');
    switch (snapshot.state) {
      case firebase.storage.TaskState.PAUSED: // or 'paused'
        console.log('Upload is paused');
        break;
      case firebase.storage.TaskState.RUNNING: // or 'running'
        console.log('Upload is running');
        break;
    }
  }, function(error) {
    // Handle unsuccessful uploads
  }, function() {
    // Handle successful uploads on complete
    // For instance, get the download URL: https://firebasestorage.googleapis.com/...
    uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
      console.log('File available at', downloadURL);
  });
});

}
javascript html image firebase-storage
3个回答
0
投票

[nameselectedFile的属性,并且此错误表示selectedFile不存在/在尝试读取它时未定义。


0
投票

[正如我所看到的,您使用了两个不同的函数来完成工作,首先是获取输入即handleFileSelect,另一个是uploadFile,所以我认为范围绑定存在问题。变量位于您要访问的另一个范围内。您只需要在访问变量之前先对其进行初始化。

比上载函数获取该文件的实例。您可以直接使用标签id来访问

function uploadFile () {
   var selectedFile = document.getElementById('file');
  ---------- than same as you code ------------------
}

0
投票

您的问题是,您永远不会填充引用dom元素的变量。您应该确保在上载File函数之前调用了handleFileSelect函数]

<input type="file" onchange="handleFileSelect(this)" id="file">

但是这很容易出错,您很快就会遇到全局变量的问题。我建议您改进handleFileSelect以返回dom节点引用,并像这样使用它而不是使用全局变量:

function handleFileSelect() {
    $(".upload-group").show();
    return document.getElementById('file').files[0];
};

function uploadFile() {
  var filename = handleFileSelect().name;

© www.soinside.com 2019 - 2024. All rights reserved.