使用 HTML5 和 Javascript 从桌面上传(拖放)

Upload from desktop with HTML5 and Javascript (drag and drop)

我正在做一个典型的拖放操作,用于将图像从桌面上传到浏览器,我可以将内容拖放到框中,然后 console.log 在浏览器控制台中查看内容:

File { name: "deam230mthumb.jpg", lastModified: 1194641808000, lastModifiedDate: Date 2007-11-09T20:56:48.000Z, size: 60313, type: "image/jpeg" }

我想在框内查看图片,然后在提交时上传。

这里我的代码是使用 Jade 模板引擎:

翡翠 (HTML)

form(action="" enctype="multipart/form-data")
 div(class="all-100 miniatures")
 div(class="all-100 drop ink-droppable align-center fallback" id="dropZone" ondrop="drop(event)" ondragover="allowDrop(event)")

Javascript

script.
      var dropZone = document.getElementById('dropZone');
      function allowDrop(e){
        e.preventDefault();
      }

      function drop(e){
        var file = e.dataTransfer.files[0];
        e.preventDefault();
        console.log(file);
        //e.target.appendChild(file);

      }

好的,我的 Javascript 现在看起来是这样的:

At this point we can drag images from our desktop to browser and view them, now, we need to upload that files.

script.
      var dropZone = document.getElementById('dropZone');
      function allowDrop(e){
        e.preventDefault();
      }

      function drop(e){
        var file = e.dataTransfer.files[0];
        e.preventDefault();
        console.log(file);
        var reader = new FileReader();
        reader.onload = function(event){
          var miniatures = document.getElementById('miniatures');
          var miniature = new Image();
          miniature.src = event.target.result;
          miniature.width = 100;
          miniatures.appendChild(miniature);
        }
        reader.readAsDataURL(file);
      }

I added an array for content each file from the event, on the following code we need to add a controller for handle each file from the array with a register of each one on the database.

script.
      var dropZone = document.getElementById('dropZone');
      function allowDrop(e){
        e.preventDefault();
      }
      var files = [];
      function drop(e){
        var file = e.dataTransfer.files[0];
        files.push(file);
        console.log(file)
        e.preventDefault();

        var reader = new FileReader();
        reader.onload = function(event){
          var miniatures = document.getElementById("miniatures");      
          var img = new Image();
          img.src = event.target.result;
          var miniature = document.createElement("div");
          miniature.className = "all-20";
          miniature.appendChild(img);
          miniatures.appendChild(miniature);               
        }
        var readerContent = reader.readAsDataURL(file);
        var input = document.getElementById("upload");
        input.files = readerContent;
        console.log(files);
      }