簡體   English   中英

Firebase Storage 和 Dropzone.js 多張圖片上傳按鈕按下

[英]Firebase Storage and Dropzone.js multiple image upload on button press

基本上我想要做的是允許人們添加文件,然后按下按鈕將圖像上傳到 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.');
    }
  });
}

我正在努力實現的目標

我想將上述上傳功能合並到以下代碼段中。 當我按提交 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>

您可以使用 ' addedfile' 事件來觸發您的自定義上傳功能,如下所示:

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

並完全省略 dropzone 上傳功能。

要獲取進度數據,請僅使用firebase put().on(state_changed)方法並再次省略 dropzone 進度。

您現在可能已經解決了這個問題,所以我很想對這個答案提供一些反饋,因為我目前正在使用 dropzone 和 firebase。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM