上传多个文件并删除按钮

时间:2015-09-29 16:02:51

标签: jquery

所以我的代码允许用户点击图标而不是选择要上传的文件。每次他们点击图标新INPUT字段添加类型“文件”,名称相同 - “文件[]”(数组)。

我要做的是允许上传多个文件。每次使用选择文件我想打印它的名称并在其旁边添加“删除”按钮。

我该怎么做?

这就是我现在所拥有的: (hide = display:none)

<form class="form-horizontal" action='#' method="post"  enctype="multipart/form-data">

    <img class="uploadFileImg" alt="" src="images/photoIconOn.png"> <br /><br/>
    <span class="fileNameBox"></span>
    <input type='file' name='file[]' class='file-field hide' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif" />

</form>

JS:

$(".uploadFileImg").on('click',function(){
   $(".file-field").trigger('click'); 

    var new_field = $("<input type='file[]' class='form-control file-field hide'>");
    $(this).closest('form').append(new_field);     

}); 

删除文件:

$(function() {
    $(document).on('click','.clear_file',function() {
        $(this).closest('form').find('input.file-field').val("")
        $(this).closest('form').find('.fileNameBox').html("");
  });
});

1 个答案:

答案 0 :(得分:0)

由于您使用的是jQuery和Bootstrap,我们将坚持使用它。

所以我们需要两个输入组:

  1. 带有添加选项的默认选项
  2. 隐藏的一个带有删除选项
  3. 这就是HTML的样子:

    <form id="form" class="form-horizontal" method="POST" accept-charset="UTF-8" enctype="multipart/form-data">
        <div class="form-group">
            <label class="col-xs-2 control-label" for="file">Upload Image</label>
            <div class="col-xs-8">
                <input id="file" class="form-control" type="file" name="file[]" accept="image/*">
            </div>
            <div class="col-xs-2">
                <button class="btn btn-default add" type="button"><i class="glyphicon glyphicon-plus" aria-hidden="true"></i></button>
            </div>
        </div>
        <!-- START FILE UPLOAD TEMPLATE -->
        <div id="upload-template" class="form-group hide">
            <div class="col-xs-offset-2 col-xs-8">
                <input id="file" class="form-control" type="file" name="file[]" accept="image/*">
            </div>
            <div class="col-xs-2">
                <button class="btn btn-default remove" type="button"><i class="glyphicon glyphicon-minus" aria-hidden="true"></i></button>
            </div>
        </div>
        <!-- END FILE UPLOAD TEMPLATE -->
    </form>
    

    然后,我们只需在有人点击+按钮时克隆隐藏的模板组,并在有人点击-按钮时将其删除:

    $('#form')
    .on('click', '.add', function () {
        var $template = $('#upload-template');
        var $clone    = $template.clone().removeClass('hide').removeAttr('id').insertBefore($template);
    
        $clone.find('[name="file[]"]');
    }).on('click', '.remove', function () {
        var $row = $(this).closest('.form-group');
    
        $row.find('[name="file[]"]');
    
        $row.remove();
    });
    

    你可以在这里看到一个关于JSFiddle的工作示例:

    https://jsfiddle.net/divspace/pwepeez1/