【问题标题】:jQuery File Upload: Detect if same file selectedjQuery文件上传:检测是否选择了相同的文件
【发布时间】:2014-12-03 19:23:54
【问题描述】:

我为我的网站使用 jQuery File Upload 插件。

用户按下“浏览...”按钮后,我调用 uploadadd 回调。 但是,它会触发每次用户添加文件。即使他添加了相同的文件。

我需要对每个唯一文件仅触发一次 uploadadd 回调,或者获取文件的唯一标识符,以便将其存储在文件数组中。在这种情况下,我可以检测文件是否已被选中。

我尝试使用回调函数的数据数组:

function (e, data) { }

但它仅包含文件大小/文件名/文件类型信息,因此我无法从中创建唯一哈希,因为两个或多个文件可以具有相同的信息。

这是我的代码:

$('#fileupload').fileupload({
    url: "/upload/",
    dataType: 'json',
    autoUpload: false,
    add: function (e, data) {
        console.log(data.files[0]);
        qcount += 1;
        $('#select-button').text(qcount + ' files');

        data.submit();
    });
});

在 Uploadify 插件中,我可以使用 onAddQueueItem 回调,但 jQuery-File-Upload 似乎没有相同的功能。

提前致谢!

【问题讨论】:

    标签: javascript jquery file-upload uploadify jquery-file-upload


    【解决方案1】:

    试试这样的:

    $('#fileupload').fileupload({
        url: "/upload/",
        dataType: 'json',
        autoUpload: false,
        add: function (e, data) {
            data.files = $.map(data.files, function(file,i){
                if ($.inArray(file.name,currentfiles) >= 0) { 
                    alert("file exists");
                    return null; 
                }
                return file;
            });
    
            console.log(data.files[0]);
            qcount += 1;
            $('#select-button').text(qcount + ' files');
    
            data.submit();
        });
    });
    

    您不必使用file.name。您可以使用 file.name + file.size 作为哈希。

    【讨论】:

    • 我不能使用 file.name + file.size 作为哈希,因为它不安全。如果有两个名为“1.jpg”且大小为 1024 字节的文件怎么办?
    • 好吧,我试过你的源代码,但是当我上传两个不同的图像但文件名和文件大小相同时它失败了。
    • 哪个对您更重要 - 两个具有相同名称和文件大小的文件?您始终可以在后端编写代码以捕获其中一个。我认为在前端捕获相同的文件大小和文件名会更有意义,但如果你想让人们这样做,那么,好吧。
    • 我需要在前端捕获它以显示文件数。您的代码无法做到这一点。它不计算具有相同名称和大小的不同文件。我需要的是计算每个文件,不包括它自己。
    猜你喜欢
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2021-11-02
    • 2018-04-01
    相关资源
    最近更新 更多