jQuery 使用 HTML5 文件输入时单击按钮从多个文件上传器中删除文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32062876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:50:37  来源:igfitidea点击:

Removing file from multiple files uploader on button click when using HTML5 file input

jqueryhtmlmultifile-uploader

提问by u4701744

How to add removebutton here like simple remove one by one in files queue like this

如何在此处添加删除按钮,就像这样在文件队列中简单地一一删除

enter image description here

在此处输入图片说明

The reason why im not using free file upload plugins with OOB plugs because my client requirements is for security purposes and they need simple upload ui without any complicated plugins.

我之所以不使用带有 OOB 插件的免费文件上传插件,是因为我的客户要求是出于安全目的,他们需要简单的上传 ui,没有任何复杂的插件。

$(function() {
  var dropZoneId = "drop-zone";
  var buttonId = "clickHere";
  var mouseOverClass = "mouse-over";

  var dropZone = $("#" + dropZoneId);
  var ooleft = dropZone.offset().left;
  var ooright = dropZone.outerWidth() + ooleft;
  var ootop = dropZone.offset().top;
  var oobottom = dropZone.outerHeight() + ootop;
  var inputFile = dropZone.find("input");
  document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
    e.preventDefault();
    e.stopPropagation();
    dropZone.addClass(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
      inputFile.offset({
        top: y - 15,
        left: x - 100
      });
    } else {
      inputFile.offset({
        top: -400,
        left: -400
      });
    }

  }, true);

  if (buttonId != "") {
    var clickZone = $("#" + buttonId);

    var oleft = clickZone.offset().left;
    var oright = clickZone.outerWidth() + oleft;
    var otop = clickZone.offset().top;
    var obottom = clickZone.outerHeight() + otop;

    $("#" + buttonId).mousemove(function(e) {
      var x = e.pageX;
      var y = e.pageY;
      if (!(x < oleft || x > oright || y < otop || y > obottom)) {
        inputFile.offset({
          top: y - 15,
          left: x - 160
        });
      } else {
        inputFile.offset({
          top: -400,
          left: -400
        });
      }
    });
  }

  document.getElementById(dropZoneId).addEventListener("drop", function(e) {
    $("#" + dropZoneId).removeClass(mouseOverClass);
  }, true);

  inputFile.on('change', function(e) {
    $('#filename').html("");
    var fileNum = this.files.length,
      initial = 0,
      counter = 0;
    for (initial; initial < fileNum; initial++) {
      counter = counter + 1;
      $('#filename').append('<span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + '&nbsp;&nbsp;<span class="fa fa-times-circle fa-lg closeBtn" title="remove"></span><br>');
    }
  });

})
#drop-zone {
  width: 100%;
  min-height: 150px;
  border: 3px dashed rgba(0, 0, 0, .3);
  border-radius: 5px;
  font-family: Arial;
  text-align: center;
  position: relative;
  font-size: 20px;
  color: #7E7E7E;
}
#drop-zone input {
  position: absolute;
  cursor: pointer;
  left: 0px;
  top: 0px;
  opacity: 0;
}
/*Important*/

#drop-zone.mouse-over {
  border: 3px dashed rgba(0, 0, 0, .3);
  color: #7E7E7E;
}
/*If you dont want the button*/

#clickHere {
  display: inline-block;
  cursor: pointer;
  color: white;
  font-size: 17px;
  width: 150px;
  border-radius: 4px;
  background-color: #4679BD;
  padding: 10px;
}
#clickHere:hover {
  background-color: #376199;
}
#filename {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5em;
}
.file-preview {
  background: #ccc;
  border: 5px solid #fff;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  font-size: 14px;
  margin-top: 5px;
}
.closeBtn:hover {
  color: red;
}
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="drop-zone">
  <p>Drop files here...</p>
  <div id="clickHere">or click here.. <i class="fa fa-upload"></i>
    <input type="file" name="file" id="file" multiple />
  </div>
  <div id='filename'></div>
</div>

Note: I didnt own the code i've been reused it as my resources from other people and modified it for my client

注意:我不拥有代码,我已将其用作其他人的资源并为我的客户修改了它

**UPDATE Here my fiddlelink

**更新这里是我的小提琴链接

回答by KAD

The file list of HTML5 file input is readonly, so when trying to remove a file from it you won't be allowed.

HTML5 文件输入的文件列表是只读的,因此在尝试从中删除文件时,您将不被允许。

What you need to do is maintain a separate array list (JSON array as per the example).

您需要做的是维护一个单独的数组列表(如示例所示的 JSON 数组)。

I have wrapped your X button with a div that hold the file index concatenated to a 'file_' string, and added an onclickfunction removeLine(obj)that accepts the element as an object.

我已经包裹你的X按钮,持有级联到“_文件”字符串的文件索引一个div,并增加了一个onclick功能removeLine(obj),它接受元素作为对象。

I have also added a JSON array finalFilesin the global scope as well as moved the inputFileto the global scope.

我还在finalFiles全局范围内添加了一个 JSON 数组,并将 移动inputFile到全局范围。

When the file input changes, I am setting the JSON array with the selected files through :

当文件输入更改时,我通过以下方式使用所选文件设置 JSON 数组:

$.each(this.files,function(idx,elm){
           finalFiles[idx]=elm;
        });

The function removeLinewill flush the input file list to allow the same file selection again if the user removed the file by mistake, the function obtains the file index from the wrapper division id, removes the wrapper div then deletes the file from the JSON array.

removeLine如果用户错误地删除了文件,该函数将刷新输入文件列表以允许再次选择相同的文件,该函数从包装器部门 id 中获取文件索引,删除包装器 div,然后从 JSON 数组中删除文件。

function removeLine(obj)
    {
      inputFile.val('');
      var jqObj = $(obj);
      var container = jqObj.closest('div');
      var index = container.attr("id").split('_')[1];
      container.remove(); 

      delete finalFiles[index];
      //console.log(finalFiles);
    }

You can the maintain your files when the form submits and send them through AJAX post using FormData in a similar manner to This Article.

您可以保持你的文件表单提交时,通过AJAX后使用FORMDATA以类似的方式将它们发送到这条

var dropZoneId = "drop-zone";
  var buttonId = "clickHere";
  var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
 var inputFile = dropZone.find("input");
 var finalFiles = {};
$(function() {
  

  
  var ooleft = dropZone.offset().left;
  var ooright = dropZone.outerWidth() + ooleft;
  var ootop = dropZone.offset().top;
  var oobottom = dropZone.outerHeight() + ootop;
 
  document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
    e.preventDefault();
    e.stopPropagation();
    dropZone.addClass(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
      inputFile.offset({
        top: y - 15,
        left: x - 100
      });
    } else {
      inputFile.offset({
        top: -400,
        left: -400
      });
    }

  }, true);

  if (buttonId != "") {
    var clickZone = $("#" + buttonId);

    var oleft = clickZone.offset().left;
    var oright = clickZone.outerWidth() + oleft;
    var otop = clickZone.offset().top;
    var obottom = clickZone.outerHeight() + otop;

    $("#" + buttonId).mousemove(function(e) {
      var x = e.pageX;
      var y = e.pageY;
      if (!(x < oleft || x > oright || y < otop || y > obottom)) {
        inputFile.offset({
          top: y - 15,
          left: x - 160
        });
      } else {
        inputFile.offset({
          top: -400,
          left: -400
        });
      }
    });
  }

  document.getElementById(dropZoneId).addEventListener("drop", function(e) {
    $("#" + dropZoneId).removeClass(mouseOverClass);
  }, true);


  inputFile.on('change', function(e) {
    finalFiles = {};
    $('#filename').html("");
    var fileNum = this.files.length,
      initial = 0,
      counter = 0;

    $.each(this.files,function(idx,elm){
       finalFiles[idx]=elm;
    });

    for (initial; initial < fileNum; initial++) {
      counter = counter + 1;
      $('#filename').append('<div id="file_'+ initial +'"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + '&nbsp;&nbsp;<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
    }
  });



})

function removeLine(obj)
{
  inputFile.val('');
  var jqObj = $(obj);
  var container = jqObj.closest('div');
  var index = container.attr("id").split('_')[1];
  container.remove(); 

  delete finalFiles[index];
  //console.log(finalFiles);
}
#drop-zone {
  width: 100%;
  min-height: 150px;
  border: 3px dashed rgba(0, 0, 0, .3);
  border-radius: 5px;
  font-family: Arial;
  text-align: center;
  position: relative;
  font-size: 20px;
  color: #7E7E7E;
}
#drop-zone input {
  position: absolute;
  cursor: pointer;
  left: 0px;
  top: 0px;
  opacity: 0;
}
/*Important*/

#drop-zone.mouse-over {
  border: 3px dashed rgba(0, 0, 0, .3);
  color: #7E7E7E;
}
/*If you dont want the button*/

#clickHere {
  display: inline-block;
  cursor: pointer;
  color: white;
  font-size: 17px;
  width: 150px;
  border-radius: 4px;
  background-color: #4679BD;
  padding: 10px;
}
#clickHere:hover {
  background-color: #376199;
}
#filename {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5em;
}
.file-preview {
  background: #ccc;
  border: 5px solid #fff;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  font-size: 14px;
  margin-top: 5px;
}
.closeBtn:hover {
  color: red;
  display:inline-block;
}
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="drop-zone">
  <p>Drop files here...</p>
  <div id="clickHere">or click here.. <i class="fa fa-upload"></i>
    <input type="file" name="file" id="file" multiple />
  </div>
  <div id='filename'></div>
</div>

回答by Matt Komarnicki

I've done this before for my Dropzone. Feel free to adjust. This is from my Laravel app. You should focus on avatar_refresh_upload. Cut off unnecessary stuff and you're done.

我以前为我的 Dropzone 做过这个。随意调整。这是来自我的 Laravel 应用程序。你应该专注于avatar_refresh_upload. 切断不必要的东西,你就完成了。

function avatar_refresh_upload() {
    var input = $('input#avatar[type=file]');

    input.replaceWith(input.val('').clone(true));

    $('#selected_file').html('{{ Lang::get('app.profile_avatar_select') }}');
    $('#avatar_refresh_upload').removeAttr('style');
}

$(document).ready(function ($) {

    $('input:file#avatar').change(function () {
        var file_name = $(this).val();
        if (file_name.length > 10) {
            file_name = file_name.substring(0, 10) + '...';
        }
        $('#selected_file').html('File "' + file_name + '" chosen');
        $('#avatar_refresh_upload').css('display', 'inline-block');
    });

    $('#avatar_refresh_upload').on('click', function () {
        avatar_refresh_upload();
    });

    @if ($user->avatar != '')
    $('#remove_avatar').change(function () {

        if ($(this).is(':checked')) {

            avatar_refresh_upload();
            $('#avatar').prop('disabled', true);
            $('#avatar_preview').css('opacity', '0.5');
            $('#avatar_upload_form_area').css('opacity', '0.5');
            $('#remove_avatar_info').show();

        } else {

            $('#avatar').prop('disabled', false);
            $('#avatar_preview').removeAttr('style');
            $('#avatar_upload_form_area').removeAttr('style');
            $('#remove_avatar_info').removeAttr('style');

        }
    });
    @endif

});

Making long story short - if you want to reset input file after you picked a file for upload but before submitting, you have to run:

长话短说 -如果您想在选择要上传的文件后但在提交之前重置输入文件,则必须运行

input.replaceWith(input.val('').clone(true));

回答by Padhraic

Since we cannot modify the selected files array in the <input type'file' multiple>tag then I have updated you code to show the count of file and to delete all the files if multiple files are selected.

由于我们无法修改<input type'file' multiple>标签中选定的文件数组,因此我更新了您的代码以显示文件计数并在选择多个文件时删除所有文件。

There is a fiddle of the updated code.

有一个更新的代码小提琴。

$(function () {
    var dropZoneId = "drop-zone";
    var buttonId = "clickHere";
    var mouseOverClass = "mouse-over";

    var dropZone = $("#" + dropZoneId);
    var ooleft = dropZone.offset().left;
    var ooright = dropZone.outerWidth() + ooleft;
    var ootop = dropZone.offset().top;
    var oobottom = dropZone.outerHeight() + ootop;
    var inputFile = dropZone.find("input");
    document.getElementById(dropZoneId).addEventListener("dragover", function (e) {
        e.preventDefault();
        e.stopPropagation();
        dropZone.addClass(mouseOverClass);
        var x = e.pageX;
        var y = e.pageY;

        if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
            inputFile.offset({
                top: y - 15,
                left: x - 100
            });
        } else {
            inputFile.offset({
                top: -400,
                left: -400
            });
        }

    }, true);

    if (buttonId != "") {
        var clickZone = $("#" + buttonId);

        var oleft = clickZone.offset().left;
        var oright = clickZone.outerWidth() + oleft;
        var otop = clickZone.offset().top;
        var obottom = clickZone.outerHeight() + otop;

        $("#" + buttonId).mousemove(function (e) {
            var x = e.pageX;
            var y = e.pageY;
            if (!(x < oleft || x > oright || y < otop || y > obottom)) {
                inputFile.offset({
                    top: y - 15,
                    left: x - 160
                });
            } else {
                inputFile.offset({
                    top: -400,
                    left: -400
                });
            }
        });
    }

    document.getElementById(dropZoneId).addEventListener("drop", function (e) {
        $("#" + dropZoneId).removeClass(mouseOverClass);
    }, true);

    inputFile.on('change', function (e) {
        $('#filename').html("");
        var fileNum = this.files.length,
            initial = 0,
            counter = 0,
            fileNames = "";

        for (initial; initial < fileNum; initial++) {
            counter = counter + 1;
            fileNames += this.files[initial].name + '&nbsp;';
        }
        if(fileNum > 1)
            fileNames = 'Files selected...';
        else
            fileNames = this.files[0].name + '&nbsp;';

        $('#filename').append('<span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">'+ fileNum + '</strong></span><span">' + fileNames + '</span>&nbsp;<span class="fa fa-times-circle fa-lg closeBtn" title="remove"></span><br>');

        // add remove event
      $('#filename').find('.closeBtn').click(function(){
          $('#filename').empty();
          inputFile.val('');
      });
      ///End change 
    });

})

回答by Code Uniquely

$(function () {

  var dropZoneId = "drop-zone";
  var buttonId = "clickHere";
  var mouseOverClass = "mouse-over";

  var dropZone = $("#" + dropZoneId);
  var ooleft = dropZone.offset().left;
  var ooright = dropZone.outerWidth() + ooleft;
  var ootop = dropZone.offset().top;
  var oobottom = dropZone.outerHeight() + ootop;
  var inputFile = dropZone.find("input");

  var filesArr = [];

  function showFiles() {
    $('#filename').html("");
    var fileNum = filesArr.length;
    for (var i = 0; i < fileNum; i++) {
      $('#filename').append('<div><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">'+ i + '</strong></span> ' + filesArr[i].name + '&nbsp;&nbsp;<span class="fa fa-times-circle fa-lg closeBtn" title="remove"></span></div>');
      }
  }

  function addFiles(e) {
    var tmp;

    // transfer dropped content to temporary array
    if (e.dataTransfer) {
      tmp = e.dataTransfer.files;
    } else if (e.target) {
      tmp = e.target.files;
    }        

    // Copy the file items into the array 
    for(var i = 0; i < tmp.length; i++) {
      filesArr.push(tmp.item(i));
    }

    // remove all contents from the input elemnent (reset it)
    inputFile.wrap('<form>').closest('form').get(0).reset();
    inputFile.unwrap();

    showFiles();
  }    

  document.getElementById(dropZoneId).addEventListener("dragover", function (e) {
    e.preventDefault();
    e.stopPropagation();
    dropZone.addClass(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
        inputFile.offset({
            top: y - 15,
            left: x - 100
        });
    } else {
        inputFile.offset({
            top: -400,
            left: -400
        });
    }
  }, true);

  if (buttonId != "") {
    var clickZone = $("#" + buttonId);

    var oleft = clickZone.offset().left;
    var oright = clickZone.outerWidth() + oleft;
    var otop = clickZone.offset().top;
    var obottom = clickZone.outerHeight() + otop;

    $("#" + buttonId).mousemove(function (e) {
      var x = e.pageX;
      var y = e.pageY;
      if (!(x < oleft || x > oright || y < otop || y > obottom)) {
          inputFile.offset({
              top: y - 15,
              left: x - 160
          });
      } else {
          inputFile.offset({
              top: -400,
              left: -400
          });
      }
    });
  }
  document.getElementById(dropZoneId).addEventListener("drop", function (e) {
    $("#" + dropZoneId).removeClass(mouseOverClass);
    addFiles(e);
  }, true);

  inputFile.on('change', function(e) {
    addFiles(e);
  });

  $('#filename').on('click', '.closeBtn', function(e) {
    e.preventDefault();
    e.stopPropagation();

    var divElem = $(this).parent();
    var index = $('#filename').find('div').index(divElem);
    if ( index !== -1 ) {
      $('#filename')[0].removeChild(divElem[0]);
      filesArr.slice(index,1);
    }
  });

})

回答by Erik

$(function () {

  var dropZoneId = "drop-zone";
  var buttonId = "clickHere";
  var mouseOverClass = "mouse-over";

  var dropZone = $("#" + dropZoneId);
  var ooleft = dropZone.offset().left;
  var ooright = dropZone.outerWidth() + ooleft;
  var ootop = dropZone.offset().top;
  var oobottom = dropZone.outerHeight() + ootop;
  var inputFile = dropZone.find("input");

  var filesArr = [];

  function showFiles() {
    $('#filename').html("");
    var fileNum = filesArr.length;
    for (var i = 0; i < fileNum; i++) {

                                objectURL = URL.createObjectURL(filesArr[i]);

      $('#filename').append('<div><img title="'+filesArr[i].name+'" id="'+objectURL+'" src="'+objectURL+'" class="pre-visualizacao"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">'+ i + '</strong></span> ' + filesArr[i].name + '&nbsp;&nbsp;<span class="closeBtn" title="Remover">X</span></div>');

      }
  }

  function addFiles(e) {
    var tmp;

    // transfer dropped content to temporary array
    if (e.dataTransfer) {
      tmp = e.dataTransfer.files;
    } else if (e.target) {
      tmp = e.target.files;
    }        

    // Copy the file items into the array 
    for(var i = 0; i < tmp.length; i++) {
      filesArr.push(tmp.item(i));
      //console.log(i);
    }

    // remove all contents from the input elemnent (reset it)
    inputFile.wrap('<form>').closest('form').get(0).reset();
    inputFile.unwrap();

    showFiles();
  }    

  document.getElementById(dropZoneId).addEventListener("dragover", function (e) {
    e.preventDefault();
    e.stopPropagation();
    dropZone.addClass(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
        inputFile.offset({
            top: y - 15,
            left: x - 100
        });
    } else {
        inputFile.offset({
            top: -400,
            left: -400
        });
    }
  }, true);

  if (buttonId != "") {
    var clickZone = $("#" + buttonId);

    var oleft = clickZone.offset().left;
    var oright = clickZone.outerWidth() + oleft;
    var otop = clickZone.offset().top;
    var obottom = clickZone.outerHeight() + otop;

    $("#" + buttonId).mousemove(function (e) {
      var x = e.pageX;
      var y = e.pageY;
      if (!(x < oleft || x > oright || y < otop || y > obottom)) {
          inputFile.offset({
              top: y - 15,
              left: x - 160
          });
      } else {
          inputFile.offset({
              top: -400,
              left: -400
          });
      }
    });
  }
  document.getElementById(dropZoneId).addEventListener("drop", function (e) {
    $("#" + dropZoneId).removeClass(mouseOverClass);
    addFiles(e);
  }, true);

  /*inputFile.on('change', function(e) {
    addFiles(e);
  });*/

  $('#filename').on('click', '.closeBtn', function(e) {
    e.preventDefault();
    e.stopPropagation();

    var divElem = $(this).parent();
    var index = $('#filename').find('div').index(divElem);
    if ( index !== -1 ) {
      $('#filename')[0].removeChild(divElem[0]);
      filesArr.slice(index,1);
    }
  });
  inputFile.on('change', function(e) {
    $('#filename').html("");
    var fileNum = this.files.length,
      initial = 0,
      counter = 0;
    for (initial; initial < fileNum; initial++) {
      counter = counter + 1;
      objectURL = URL.createObjectURL(this.files[initial]);
      $('#filename').append('<div><img title="'+this.files[initial].name+'" id="'+objectURL+'" src="'+objectURL+'" class="pre-visualizacao"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">'+ counter + '</strong></span> ' + this.files[initial].name + '&nbsp;&nbsp;<span class="closeBtn" title="Remover">X</span></div>');
    }
  });

});