【问题标题】:Firebase Storage and Dropzone.js multiple image upload on button press按下按钮时 Firebase 存储和 Dropzone.js 多张图片上传
【发布时间】:2018-07-13 10:52:10
【问题描述】:

基本上我想要做的是允许人们添加文件,然后按下按钮将图像上传到 Firebase 存储。我决定使用 Dropzone.js,因为该软件包编写良好且可自定义,但我仍然很难过。

我有这段代码,它允许我将多个图像上传到 Firebase,但是,我希望它适合此代码下方的框架:

HTML

<input type="file" id="file" name="file" multiple/>

JS

var auth = firebase.auth();
var storageRef = firebase.storage().ref();
//Handle waiting to upload each file using promise
function uploadImageAsPromise (imageFile) {
    return new Promise(function (resolve, reject) {
        var storageRef = firebase.storage().ref("/sth/"+imageFile.name);
        //Upload file
        var task = storageRef.put(imageFile);
        //Update progress bar
        task.on('state_changed',
            function progress(snapshot){
              // 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(err){

            },
            function complete(){
                var downloadURL = task.snapshot.downloadURL;
            }
        );
    });
}

window.onload = function() {
  document.getElementById('file').addEventListener('change', function(e){ 
  //Get files
      for (var i = 0; i < e.target.files.length; i++) {
          var imageFile = e.target.files[i];

          uploadImageAsPromise(imageFile);
      }
  });

  document.getElementById('file').disabled = true;
  auth.onAuthStateChanged(function(user) {
    if (user) {
      document.getElementById('file').disabled = false;
    } else {
      console.log('You need to sign in.');
    }
  });
}

我正在努力实现的目标

我想将上面的上传功能合并到下面的 sn-p 中。当我按下提交 id 时,进度条会显示和要上传的文件。 Dropzone 说我应该指定它说 URL: 但我不知道如何引用它的函数。另外,dropzone 表示该函数必须返回下载的 URL。

// Get the template HTML and remove it from the doument
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
var submitButton = document.querySelector('#submit-button');

var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
  url: "/", // Set the url
  thumbnailWidth: 80,
  thumbnailHeight: 80,
  parallelUploads: 20,
  previewTemplate: previewTemplate,
  autoQueue: false, // Make sure the files aren't queued until manually added
  previewsContainer: "#previews", // Define the container to display the previews
  clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
});

// Update the total progress bar
myDropzone.on("totaluploadprogress", function(progress) {
  document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
});

myDropzone.on("sending", function(file) {
  // Show the total progress bar when upload starts
  document.querySelector("#total-progress").style.opacity = "1";
  // And disable the start button
  file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});



submitButton.addEventListener('click', function(){

  myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));


  myDropzone.on("queuecomplete", function(progress) {
    document.querySelector("#total-progress").style.opacity = "0";

    //DO STUFF

  });
  
});
#actions {
  margin: 2em 0;
}


/* Mimic table appearance */
div.table {
  display: table;
}
div.table .file-row {
  display: table-row;
}
div.table .file-row > div {
  display: table-cell;
  vertical-align: top;
  border-top: 1px solid #ddd;
  padding: 8px;
}
div.table .file-row:nth-child(odd) {
  background: #f9f9f9;
}



/* The total progress gets shown by event listeners */
#total-progress {
  opacity: 0;
  transition: opacity 0.3s linear;
}

/* Hide the progress bar when finished */
#previews .file-row.dz-success .progress {
  opacity: 0;
  transition: opacity 0.3s linear;
}

/* Hide the delete button initially */
#previews .file-row .delete {
  display: none;
}

/* Hide the start and cancel buttons and show the delete button */

#previews .file-row.dz-success .start,
#previews .file-row.dz-success .cancel {
  display: none;
}
#previews .file-row.dz-success .delete {
  display: block;
}
<!DOCTYPE html>
<!--[if IE 9]> <html lang="zxx" class="ie9"> <![endif]-->
<!--[if gt IE 9]> <html lang="zxx" class="ie"> <![endif]-->
<!--[if !IE]><!-->
<html dir="ltr" lang="zxx">
  <!--<![endif]-->

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <!-- Import and configure the Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script>
      // Initialize Firebase
      var config = {
        apiKey: "<your-api-key>",
        authDomain: "<your-auth-domain>",
        databaseURL: "<your-database-url>",
        projectId: "<your-project-id>",
        storageBucket: "<your-storage-bucket>",
        messagingSenderId: "<your-messaging-id>"
      };
      firebase.initializeApp(config);
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.2.0/dropzone.js"></script>

  </head>

  <body class=" ">

    <!-- banner start -->
    <!-- ================ -->
    <div class="pv-40 banner light-gray-bg">
      <div class="container clearfix">
        <h3>Add Images</h3>

        <div id="actions" class="row">

          <div class="col-lg-7">
            <!-- The fileinput-button span is used to style the file input field as button -->
            <span class="btn btn-success fileinput-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>Add files...</span>
            </span>
          </div>

        </div>

        <div class="table table-striped files" id="previews">

          <div id="template" class="file-row">
            <!-- This is used as the file preview template -->
            <div>
                <span class="preview"><img data-dz-thumbnail /></span>
            </div>
            <div>
                <p class="name" data-dz-name></p>
                <strong class="error text-danger" data-dz-errormessage></strong>
            </div>
            <div>
                <p class="size" data-dz-size></p>
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                  <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
                </div>
            </div>
            <div>
              <button data-dz-remove class="btn btn-warning cancel">
                  <i class="glyphicon glyphicon-ban-circle"></i>
                  <span>Cancel</span>
              </button>
              <button data-dz-remove class="btn btn-danger delete">
                <i class="glyphicon glyphicon-trash"></i>
                <span>Delete</span>
              </button>
            </div>
          </div>

        </div>

      </div>
    </div>
      <!-- banner end -->
      <!-- main-container start -->
      <!-- ================ -->
    <section class="main-container padding-ver-clear">
      <div class="container pv-40">         
        <div style="text-align: center;">
          <button id="submit-button" type="submit" value="Submit" class="btn btn-danger btn-lg start">Submit <i class="fa fa-external-link"></i></button>
          <div class="col-lg-5">
            <!-- The global file processing state -->
            <span class="fileupload-process">
              <div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
              </div>
            </span>
          </div>
        </div>
      </div>
    </section>
    
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

  </body>
</html>

【问题讨论】:

    标签: javascript jquery html firebase-storage dropzone.js


    【解决方案1】:

    您可以使用 'addedfile' 事件来触发您的自定义上传功能,如下所示:

    myDropzone.on("addedfile", function(){
        uploadImageAsPromise(file);
    });
    

    并完全省略 dropzone 上传功能。

    要获取进度数据,请仅使用 firebase put().on(state_changed) 方法并再次省略 dropzone 进度。

    你现在可能已经解决了这个问题,所以我希望得到一些关于这个答案的反馈,因为我目前正在使用 dropzone 和 firebase。

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2020-08-14
      • 2017-06-29
      相关资源
      最近更新 更多