如何从输入类型文件中删除多个特定文件?

时间:2017-09-21 00:49:24

标签: javascript jquery html5

我正在使用输入类型文件多次来更新一些图片。在上传之前,页面显示每张图片的缩略图。我想删除每张图片的链接,当用户点击时,图片会消失并且文件会从输入中删除。

我尝试使用以下代码:

HTML:

<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" /> 
<div id="midiaDigital"></div>

使用Javascript:

$(document).ready(function() {

$("#midiasUpload").on('change', function() {
    //Get count of selected files
    var countFiles = $(this)[0].files.length;
    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
    var image_holder = $("#midiaDigital");
    image_holder.empty();
    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
      if (typeof(FileReader) != "undefined") {
        //loop for each file selected for uploaded.
        for (var i = 0; i < countFiles; i++) 
        {
          var reader = new FileReader();
          reader.onload = function(e) {
              $(image_holder).append('<div class="form-group row">' +
                                      '<div>' +
                                      '<div class="col-md-6">' +                              
                                      '<img src="' + e.target.result + '" class="thumb-image img-responsive">' +
                                      '<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' + 
                                      '<a href="#" class="remove_field1">Remover</a>' + //add input box
                                      '</div>' +
                                      '</div>' +
                                      '</div>'); 


          }
          image_holder.show();
          reader.readAsDataURL($(this)[0].files[i]);
        }
      } else {
        alert("O browser não suporta upload de arquivos.");
      }
    } else {
      alert("Formato de arquivo inválido");
    }
  });

$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); 
})

}); 

使用此代码,“预览”图片会显示“删除”链接。当我单击“删除”时,预览图片被删除,但文件继续被选中。我该怎么办?

2 个答案:

答案 0 :(得分:0)

你可以通过jQuery在一行中完成:$('#midiasUpload').val('');。它重置输入值。这是片段:

&#13;
&#13;
function select(el) {
  img = el;
}
var img;
var input;
$(document).ready(function() {
  $("#midiasUpload").on('change', function() {
    var countFiles = $(this)[0].files.length;
    input = $(this)[0];
    console.log('Input value after upload: ', input.value)
    var imgPath = input.value;
    img = imgPath;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
    var image_holder = $("#midiaDigital");
    image_holder.empty();
    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
      if (typeof(FileReader) != "undefined") {
        for (var i = 0; i < countFiles; i++) {
          var reader = new FileReader();
          reader.onload = function(e) {
            $(image_holder).append('<div class="form-group row">' +
                                   '<div>' +
                                   '<div class="col-md-6">' +                             
                                   '<img src="' + e.target.result + '" class="thumb-image img-responsive" onclick="select($(this))">' +
                                   '<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' + 
                                   '<a href="#" class="remove_field1">Remover</a>' + //add input box
                                   '</div>' +
                                   '</div>' +
                                   '</div>'); 
          }
          image_holder.show();
          reader.readAsDataURL($(this)[0].files[i]);
        }
      } else {
        alert("O browser não suporta upload de arquivos.");
      }
    } else {
      alert("Formato de arquivo inválido");
    }
  });

  $(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); 
    img.val = '';
    input.value = null;
    console.log('Input value after remove: ', input.value)
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" /> 
<div id="midiaDigital" style="margin-bottom: 100px;"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

请在$(image_holder).append(函数

中更改此代码
'<a href="#" data-id="'+i+'" class="remove_field1">Remover</a>' + //add input box

单击remove_field1

后,此代码有效
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); 
    var deletedId=$(this).prop("data-id");
    var names = [];
    for (var i = 0; i < $("#midiasUpload").get(0).files.length; ++i) {
     if(deletedId==i){}else{  names.push($("#midiasUpload").get(0).files[i].name);  }
    }
    $("#midiasUpload").val(names);
});