Cannot remove files from file list using JQuery-File-Upload

前端 未结 5 1609
鱼传尺愫
鱼传尺愫 2020-12-20 17:59

I have an issue using the JQuery-File-Upload plugin. I am using the plugin directly and not through the author\'s provided html example pages. Basically I have a form with s

5条回答
  •  天涯浪人
    2020-12-20 18:44

    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. 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('
  • ' + file.fileName + ' ' + ' Remove
  • '); }); },

提交回复
热议问题