HTML5输入类型=“文件”不会触发handleFileSelect()

时间:2015-08-18 08:21:49

标签: javascript jquery html5 firebase

我有这个用于将.jpg文件上传到firebase的JS代码:

    function handleFileSelect(evt) {
      var f = evt.target.files[0];
      var reader = new FileReader();
      reader.onload = (function(theFile) {
        return function(e) {
          var filePayload = e.target.result;
          // Generate a location that can't be guessed using the file's contents and a random number
          var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));
          var f = new Firebase(firebaseRef + 'pano/' + hash + '/filePayload');
          spinner.spin(document.getElementById('spin'));
          // Set the file payload to Firebase and register an onComplete handler to stop the spinner and show the preview
          f.set(filePayload, function() { 
            spinner.stop();
            document.getElementById("pano").src = e.target.result;
            $('#file-upload').hide();
            // Update the location bar so the URL can be shared with others
            window.location.hash = hash;
          });
        };
      })(f);
      reader.readAsDataURL(f);
    }
$(function() {
  $('#spin').append(spinner);

  var idx = window.location.href.indexOf('#');
  var hash = (idx > 0) ? window.location.href.slice(idx + 1) : '';
  if (hash === '') {
    // No hash found, so render the file upload button.
    $('#file-upload').show();
    document.getElementById("file-upload").addEventListener('change', handleFileSelect, false);
  } else {
    // A hash was passed in, so let's retrieve and render it.
    spinner.spin(document.getElementById('spin'));
    var f = new Firebase(firebaseRef + '/pano/' + hash + '/filePayload');
    f.once('value', function(snap) {
      var payload = snap.val();
      if (payload != null) {
        document.getElementById("pano").src = payload;
      } else {
        $('#body').append("Not found");
      }
      spinner.stop();
    });
  }
});

我的js导入:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script src="//cdn.firebase.com/v0/firebase.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/spin.js/1.2.7/spin.min.js"></script>
  <script src="sha256.js"></script>
  <script src="firepano.js"></script>

我的HTML看起来像这样:

<input type="file" accept="image/*" capture="camera" id="file-upload">

当然这只是一个部分,但是当我选择一个文件时,只有当我将HTML代码放在我的文件之外的单独文件中并且只保留此输入标记时,才会触发js函数。是否有其他一些代码可以在selectfile函数触发器中进行干预?

1 个答案:

答案 0 :(得分:1)

试试这个:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="Upload">
</form>