在div标签中显示多个附加文档名称,并在单击时删除单个文档。

时间:2017-03-24 04:08:53

标签: javascript jquery html css file-upload

我一直在尝试使用JQuery实现此功能,当使用输入字段上传文件时,我想添加div标签以及上面的文件名。 这是输入字段的代码:

 <input id="uploadBtn" type="file" name="uploadBtn" title="Upload Button" multiple>

以下是将div标签添加到其上方屏幕的功能:

     function handleFileSelect(e) {

        if(!e.target.files) return;
           var data = new FormData(); 
            var files = e.target.files;
            for(var i=0; i<files.length; i++) {
            var f = files[i];
            data.append(f.name,f);
            console.log(f.name); 
            **$('#attachedFiles').append(
                 '<div class="row"><div class="mdl-textfield mdl-js-textfield justify-space mdl-textfield--file mdl-textfield--file-is-dirty has-placeholder is-upgraded" data-upgraded=",MaterialTextfield"><input class="mdl-textfield__input" placeholder="'+f.name+'" readonly="" type="text" title="Upload File"></input> <div class="mdl-button mdl-button--primary mdl-button--icon mdl-button--file">                                       <svg role="img" aria-labelledby="remove-attachment1" height="24" viewBox="0 0 24 24"                                             width="24" xmlns="http://www.w3.org/2000/svg">                                           <title id="remove-attachment1">Remove Attachment</title>                                           <path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm6 16.538l-4.592-4.548 4.546-4.587-1.416-1.403-4.545 4.589-4.588-4.543-1.405 1.405 4.593 4.552-4.547 4.592 1.405 1.405 4.555-4.596 4.591 4.55 1.403-1.416z"></path>                                   </svg>                                     <input id="'+uploadFile[i]+  '" data-usage="' + f.name +  '"  title="Upload Button">                              </div>                                </div>                            </div>'
            );**

            }


    }

我正在尝试添加一个函数removeFiles,这样当我点击id为“uploadFile [i]”的输入字段时,它应该删除位置i的文件。此外,删除文件的功能应该返回文件名,因为我需要使用文件名来使用rest api调用从后端删除文件。

我正在尝试使用以下代码实现此目的:

 var current = [];
                     for (var i=0; i<files.length; i++) {

                          current[i]= document.getElementById(uploadFile[i]);
                                current[i].addEventListener ("click", removeFunction, false);
                     }

但是这不起作用,并且eventlistener仅附加到附加的第一个文件。 如果有人能帮助我,那就好了,因为我在这里挣扎。

3 个答案:

答案 0 :(得分:1)

您的代码提供的信息无法调试。

因此,我提供了一种不同的方法来解决您的问题。

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

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

我已将X按钮包裹在一个div中,该div将文件索引连接到&#39;文件_&#39;字符串,并添加了一个onclick函数removeLine(obj),它接受​​该元素作为对象。

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

当文件输入发生变化时,我通过以下方式设置带有所选文件的JSON数组:

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

函数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);
    }

您可以在表单提交时维护您的文件,并使用FormData以与This Article类似的方式通过AJAX帖子发送文件。

&#13;
&#13;
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);
}
&#13;
#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;
}
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

<input id="'+uploadFile[i]+  '" data-usage="' + f.name +  '"  title="Upload Button">

请检查代码的这一行。您声明输入ID不正确。 它应该是“uploadFile”+ i。

答案 2 :(得分:0)

很难在没有从您的网页上看到更多代码的情况下提供确切的建议。如果您在页面加载后向页面添加元素,那么您将无法在以后添加事件侦听器。

要解决这个问题,我会在每个文件中再添加一个类,然后在文件容器中添加一个监听器(我认为你的容器有id&#34; attachmentFiles&#34;):

HTML:

<div id="attachedFiles">
   <file1 class="attachedfile">
   <file2 class="attachedfile">
   <file3 class="attachedfile">
</div>

使用Javascript:

$('#attachedFiles').on('click', '.att-file', function() {
    // remove function
}

现在,在attachedFiles容器中出现的任何新文件都会监听点击并执行你的删除功能。