处理拖放文件夹上传html5 Chrome

时间:2014-01-17 18:19:00

标签: jquery html5 google-chrome drag-and-drop directory

我正在使用以下教程sequential file upload dnd 。我已修改脚本以添加文件和文件夹输入按钮分别上传文件和文件夹,它们按预期工作。我想处理Chrome浏览器的拖放文件夹上传。我已经查看了本网站上提出的其他问题,我可以获得遍历文件夹条目。在我的代码中,如果浏览器是非chrome我将上传已删除的文件,如果它是chrome,我将遍历文件树以查看删除的条目是文件还是文件夹,并将文件路径和名称打印到控制台。

我使用handleSequentialFileUploads()方法上传文件。我不是前端专业版,所以任何帮助都会非常感激。如何将删除的条目中的文件传递给所述handleSequentialFileUploads()方法?感谢

相关代码:

function handleSequentialFileUploads(files,obj)
{
    if(files.length == 0 ) return;
    var statusArr = [];

    for (var i = 0; i < files.length; i++) 
   {
        var status = new createStatusbar(obj); //Using this we can set progress.
        status.setFileNameSize(files[i].name,files[i].size);
        statusArr.push(status);
   }

    handleFileUpload(files,obj,statusArr,files.length); //start first file upload
}
function handleFileUpload(files,obj,statusArr,fileCount)
{
        var fd = new FormData();
        fd.append('file', files[fileCount]);
        sendFileToServer(fd,statusArr[fileCount],function()
        {
            if(fileCount == 0) {//reload();
             return; }

            var fd = new FormData();
            fd.append('file', files[fileCount]);
            handleFileUpload(files,obj,statusArr,fileCount-1); //start next file upload
        });
}

var rowCount=0;
function createStatusbar(obj)
{
     rowCount++;
     var row="odd";
     if(rowCount %2 ==0) row ="even";
     this.rowNumber=rowCount;
     this.statusbar = $("<div class='statusbar "+row+"' id='"+rowCount+"'></div>");
     this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
     this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
     this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
     this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
     obj.after(this.statusbar);

    this.setFileNameSize = function(name,size)
    {
        var sizeStr="";
        var sizeKB = size/1024;
        if(parseInt(sizeKB) > 1024)
        {
            var sizeMB = sizeKB/1024;
            sizeStr = sizeMB.toFixed(2)+" MB";
        }
        else
        {
            sizeStr = sizeKB.toFixed(2)+" KB";
        }

        this.filename.html(name);
        this.size.html(sizeStr);
    }
  this.setProgress = function(progress)
    {       
        var progressBarWidth =progress*this.progressBar.width()/ 100;  
        this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "%&nbsp;");
        if(parseInt(progress) >= 100)
        {
            this.abort.hide();
            $("#"+this.rowNumber).fadeOut(1500);
        }
    }
    this.setAbort = function(jqxhr)
    {
        var sb = this.statusbar;
        this.abort.click(function()
        {
            jqxhr.abort();
            sb.hide();
            $("#"+this.rowNumber).hide();

        });
    }
}
function sendFileToServer(formData,status,cb)
{
    var uploadURL ="";
    var extraData ={}; 
    var jqXHR=$.ajax({
            xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                    xhrobj.upload.addEventListener('progress', function(event) {
                        var percent = 0;
                        var position = event.loaded || event.position;
                        var total = event.total;
                        if (event.lengthComputable) {
                            percent = Math.ceil(position / total * 100);
                        }
                        //Set progress
                        if( typeof status!== 'undefined') 
                        status.setProgress(percent);
                    }, false);
                }
            return xhrobj;
        },
        url: uploadURL,
        type: "POST",
        contentType:false,
        processData: false,
        cache: false,
        data: formData,
        success: function(data){
         if( typeof status!== 'undefined') 
            status.setProgress(100);
            cb.call(this);
        },
        error: function (xhr, status, errMsg) 
        {
            cb.call(this);
        }
    }); 
if( typeof status!== 'undefined') 
    status.setAbort(jqXHR);
}
$(document).ready(function()
{
var obj = $("#dragzone");
var obj1=$("#dragandrophandler");
obj.on('dragenter', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
    $(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e) 
{
     e.stopPropagation();
     e.preventDefault();
});
obj.on('drop', function (e) 
{
     $(this).css('border', '2px dotted #0B85A1');
     e.preventDefault();
     //not chrome browser
     if(!isChrome){
     var files = e.originalEvent.dataTransfer.files;
     //We need to send dropped files to Server
     handleSequentialFileUploads(files,obj1);
     }
    // if chrome browser
   else {
   var items = e.originalEvent.dataTransfer.items;
   for (var i=0; i<items.length; i++) {
    var item = items[i].webkitGetAsEntry();
    if (item) {
      traverseFileTree(item);
    }

  }
  }
});
function traverseFileTree(item, path) {
  path = path || "";
  if (item.isFile) {
    // Get file
    item.file(function(file) {
      console.log("File:", path + file.name);
    });
  } 
  else if (item.isDirectory) {
    // Get folder contents
    var dirReader = item.createReader();
    dirReader.readEntries(function(entries) {
      for (var i=0; i<entries.length; i++) {
        traverseFileTree(entries[i], path + item.name + "/");
         }
        });
    }
}
$(document).on('dragenter', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
});
$(document).on('dragover', function (e) 
{
  e.stopPropagation();
  e.preventDefault();
  e.originalEvent.dataTransfer.dropEffect = 'copy';
  obj.css('border', '2px dotted #0B85A1');
  obj.css('background-color', '#cecece');



});
$(document).on('drop', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
});

});

</script>
</head>
<body>
<div id="dragzone">Drag & Drop Files Here</div>
<br>
<div class="file-input-wrapper">
<button class="btn-file-input"><img src="upload.png" border="none" style="vertical-align:middle;"/>&nbsp;&nbsp;&nbsp;Files</button>
<input type="file" class="files" id="files" name="files[]" multiple/>
</div>
<div class="file-input-wrapper">
<button class="btn-file-input"><img src="upload.png" border="none" style="vertical-align:middle;"/>&nbsp;Folder</button>
<input type="file" class="folder" id="folder" name="files[]"  mozdirectory='true' webkitdirectory ='true'/>
</div>
<br><br>
<script>
var folderin=document.getElementById('folder');
folderin.onchange = function(e) {
var folder = e.target.files; // FileList
var obj = $("#dragandrophandler");
handleSequentialFileUploads(folder,obj);
}
var filesin=document.getElementById('files');
filesin.onchange = function(e) {
var files = e.target.files; // FileList
var obj = $("#dragandrophandler");
handleSequentialFileUploads(files,obj);
}
</script>
<div id="dragandrophandler"></div>
<div class="row">
<div class="well">
</div>
</div>
</body>
</html>

0 个答案:

没有答案