简体   繁体   English

无法使用JQuery-File-Upload从文件列表中删除文件

[英]Cannot remove files from file list using JQuery-File-Upload

I have an issue using the JQuery-File-Upload plugin. 我在使用JQuery-File-Upload插件时遇到了问题。 I am using the plugin directly and not through the author's provided html example pages. 我直接使用插件而不是通过作者提供的html示例页面。 Basically I have a form with some inputs one of which is a file input. 基本上我有一个带有一些输入的表单,其中一个是文件输入。 The first upload works fine but when I attempt a second upload both files are sent (the first one for the second time) when it should only be the second one. 第一次上传工作正常,但是当我尝试第二次上传时,两个文件都被发送(第一次是第一次),而它应该只是第二次上传。

Example: 例:

  • File 1 is selected. 选择文件1。
  • File 1 is uploaded. 文件1已上传。
  • Success. 成功。
  • Using jquery I reset the form with $(FORM_SELECTOR).trigger('reset') 使用jquery我用$(FORM_SELECTOR).trigger('reset')重置表单
  • File 2 is selected. 选择文件2。
  • File 1 and file 2 are BOTH uploaded. 文件1和文件2已全部上传。
  • Problem. 问题。

Now I have two copies of file 1. This is not what I want. 现在我有两份文件1.这不是我想要的。

Obviously there isn't much point of using an ajax form upload if it only works once so I assume that there is something I am missing. 显然使用ajax表单上传没有多大意义,如果它只运行一次,所以我认为有一些我缺少的东西。

Is there a way to reset the file queue? 有没有办法重置文件队列?

When examining the data.files object I can see that the files are there after the form is reset. 检查data.files对象时,我可以看到表单重置后文件就在那里。 What can I do to sync the plugin with the input or clear out the data.files. 我该怎么做才能将插件与输入同步或清除data.files。 If I manually clear out the data.files array (via pop or data.files = []) attempting a second upload does not work. 如果我手动清除data.files数组(通过pop或data.files = []),尝试第二次上传不起作用。

I init the upload form like this: 我初始化上传表单如下:

    $('#file-upload-form').fileupload({
    url: 'uploads/upload',
    type: 'POST',
    dataType: 'json',
    multipart: true,
    dropZone: null,
    formAcceptCharset: 'utf-8',
    autoUpload: true,
    add: function (e, data) {
        fileUploadData = data;
        $("#upload-file-btn").click(function () {
            data.submit()
                .success(function (e, status, data) {
                    console.log("success response from post", status, data);
                    var i = '<input id="file-select-input" name="files[]" multiple/>';
                    $('#file-select-input').replaceWith(i);
                })
        });
    }
});

I have a custom .add event handler, in which I have called .off("click") on my button: 我有一个自定义.add事件处理程序,我在我的按钮上调用了.off(“click”):

                add: function (e, data) {

                    $('#btnstartupload').off("click");
                    data.context = $('#btnstartupload')
                        .click(function () {
                            data.submit();
                            $(".fileinput-button").hide();
                        });
}

I had the same problem and the only way I've managed to solve that was to check in the submit callback if the file was already uploaded. 我有同样的问题,我设法解决的唯一方法是检查提交回调,如果文件已经上传。 I just check if the file name is included in the array fileNames which I push the current file name before the submission and checks on the next time if the next one is present on the array and if so cancel the submission. 我只是检查文件名是否包含在数组fileNames ,我在提交之前推送当前文件名,并在下次检查下一个数组是否存在,如果是,则取消提交。

var fileNames = new Array();

$('#uploadfile').fileupload({
  submit: function(e, data) ->
    var fileName = data.files[0].name;
    if ($.inArray(fileName, fileNames) === -1)
      fileNames.push(fileName);
    else
      return false;
});

You can reset inputs quite easy. 您可以很容易地重置输入。 If that does not work for you, you might store the file somwhere. 如果这对您不起作用,您可以将文件存储在somwhere中。

DEMO DEMO

$("button#1").click(function(){
  //check file
    alert($("input").val());
      return false;
});
$("button#2").click(function(){
  //reset form
    $("form")[0].reset();
      return false;
}); 
$("button#3").click(function(){
  //replace input
    $("input").replaceWith($('<input type="file"/>'));
    return false;
}); 

I ran into the same problem. 我遇到了同样的问题。 It's puzzling why the library re-sends previously uploaded files. 令人费解的是图书馆重新发送以前上传的文件的原因。 I tried to destroy it, re-initialize it and clear/reset the actual file input field, but none of them worked. 我试图破坏它,重新初始化它并清除/重置实际的文件输入字段,但它们都没有工作。

The solution I came up with is to keep track of all upload attempts by storing file names in an array and checking in the "send" callback if a file has been already uploaded. 我想出的解决方案是通过将文件名存储在一个数组中并在已经上传文件的情况下检查“发送”回调来跟踪所有上传尝试。

Callback: 打回来:

send: function (e, data) {
            var file = data.files[0];

            // if we already attempted to upload a file with the same file name
            // do not send it in order to avoid duplicates
            if (existsInAttemptedUploads(file.name)) {
                return false;
            }
        },

Helper methods: 助手方法:

// list of file names that a user attempted to upload
var attemptedUploads = [];

// adds a file name to the list of attempted uploads
function addAttemptedUpload(fileName) {
    attemptedUploads.push(fileName);
};

// removes a given file name from the list of attempted uploads
function removeAttemptedUpload(fileName) {
    var index = $.inArray(fileName, attemptedUploads);

    if (index > -1) {
        attemptedUploads.splice(index, 1);
    }
};

// checks if a given file name is in the list of attempted uploads
function existsInAttemptedUploads(fileName) {
    var result = $.inArray(fileName, attemptedUploads);

    if (result == -1) {
        return false;
    }

    return true
};

Make sure to update the list of attemptedUploads in your "done" and "fail" callbacks and remove a file from the list if it was removed. 确保更新“完成”和“失败”回调中的attemptsUploads列表,并从列表中删除文件(如果已删除)。 For example: 例如:

done: function (e, data) {
            var id = e.target.id;

            // List all uploaded files
            $.each(data.result.files[0], function (index, file) {
                // add the current file name to the list of attempted file names
                addAttemptedUpload(file.origFileName);

                $('#uploadedFiles').append('<li id="' + file.id + '" data-orig-filename="' + file.origFileName + '">' + file.fileName + ' <a class="removeFile" href="<?php echo $deleteUrl; ?>/' + file.id + '">' + ' Remove</a></li>');
            });
        },

My code like that, when clicking the Remove link into the multiple file from JSP page, It's OK for IE11, Chrome and Firefox. 我的代码是这样的,当从JSP页面点击Remove链接到多个文件时,IE11,Chrome和Firefox都可以。

function removeFileLink(id) {
   var fileName = document.getElementById("import_file_" + id).value.replace(/^.*[\\\/]/, '');
   var objFiles = document.getElementsByName("import_fileList");
   for(var i=0; i<objFiles.length; i++){
       if(objFiles[i].value.replace(/^.*[\\\/]/, '') == fileName) {
           $(objFiles[i]).remove();                        
       }
   }
   document.getElementById("import_form").enctype="multipart/form-data";
   document.getElementById("import_form").submit();           
   return false;          
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM