蓝色恶魔文件上传插件只上传一次

10

我遇到了一个奇怪的问题,已经尝试了几种解决方案(甚至实现了官网上基本示例的相同内容)。我可以很好地上传文件,单个或多个。它们会在每个项目的点击或“全部上传”按钮时上传。问题在于尝试在上传之前或之后添加其他文件。文件上传插件甚至不会检测到文件输入中这些文件的更改,因此它永远不会触发“fileuploadadd”事件,并要求我刷新页面以上传更多文件。我在想是否丢失了fileupload更改事件,但是我无法找到原因。

此外,blueimp文件上传插件是否需要特定的JSON返回格式?目前,如果上传成功,我只返回"{\"status\":\"success\"},如果出现类似的错误消息则返回类似的消息。编辑:将响应格式更改为blueimp显示的示例没有任何效果。

这是我正在使用的上传程序的一些代码。请注意,我当前正在使用ASP.NET和jQuery 2.0.3,以及jQuery UI 1.9.2。

function initFileUploader() {
    //initProgressBars();
    $(upload_progressbar_title).css('display', 'none');
    $(upload_progressbar).css('display', 'none');
    $(upload_upload).on('click', function () {
        $(upload_progressbar).css('display', 'block');
        $(upload_progressbar_title).css('display', 'block');
        $('.uploadbtn').click();
    });
    $(upload_browse).on('click', function () {
        $(upload_file).click();
        return false;
    });

    $.guid = 0;
    console.log('initialising file upload');

    var uploadButton = $('<input type="button" id="button" />')
        .addClass('button tiny').addClass('uploadbtn')
        .prop('disabled', true)
        .val('Processing...');

    var uploadCon = $('<div class="small-4  medium-6 large-6 columns progresscontainer" />')
            .append('<div class="progressbar" />')
            .append('<label class="progressbarlabel">Not uploading</label>');

    uploadCon.append($(uploadButton).on('click', function () {
        var $this = $(this),
            data = $this.parent().data();
        $this
            .off('click')
            .val('Abort')
            .on('click', function () {
                $this.remove();
                data.abort();
            });
        data.submit().always(function () {
            $this.remove();
        }).success(function (result, textStatus, jqXHR) { console.log("Result: " + result + " - TextStatus " + textStatus); })
        .error(function (jqXHR, textStatus, errorThrown) { console.log("Error: " + errorThrown + " - TextStatus " + textStatus); })
        .complete(function (result, textStatus, jqXHR) { console.log("Result: " + result + " - TextStatus " + textStatus); });
    }));

    $(upload_file).fileupload({
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/)(pdf|jpe?g|png|doc|docx)$/i,
        maxFileSize: 5000000, // 5 MB
    }).on('fileuploadadd', function (e, data) {
        var uniqueId = $.guid++;
        data.context = $('<div id="div_upload_dcon_' + uniqueId +'" class="row"/>').appendTo(upload_filescon);
        $.each(data.files, function (index, file) {
            file.uniqueId = uniqueId;
            var node = $('<div id="div_fname" class="small-6 medium-4 large-4 columns"/>')
                    .append($('<span/>').text(file.name));
            if (!index) {
                data.url = baseUrl + 'PostUploadFile?fileName=' + data.files[index].name + '&refId=' + ClientRefId + '&upbyid=' + ClientUserId + '&ticketId=' + globalTicketId;
                var contentNode = (uploadCon.clone(true).data(data));
            }
            node.appendTo(data.context);
            $(contentNode).appendTo(data.context);
            $(upload_file).on('change', function () {
                alert('changing fileinput');
            });
        });
    }).on('fileuploadstart', function (e, data) {
        initProgressBars();
    }).on('fileuploadchange', function (e, data) {
        alert('changing');
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.error) {
            console.log(file.error));
        }
        if (index + 1 === data.files.length) {
            $('.uploadbtn').val('Upload').prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogress', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#div_upload_dcon_' + data.files[0].uniqueId).progressbar('value', progress);
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $(upload_progressbar).progressbar('value', progress);
    }).on('fileuploaddone', function (e, data) {
        getTicketContent(globalTicketId);
    }).on('fileuploadstop', function (e, data) {
        $(upload_file).val('');
    }).on('fileuploadfail', function (e, data) {
        $.each(data.files, function (index, file) {
            var error = $('<span class="text-danger"/>').text('File upload failed.');
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    });
}
2个回答

19

好的,在睡了一晚上并更多地考虑之后,我指定了这个选项

replaceFileInput: false,

在文件上传初始化期间。猜猜怎么着,现在按预期工作了。我猜文件输入被丢失是因为默认情况下文件上传会在上传或更改后克隆控件。

感谢任何人对此的考虑,我希望它对将来的某个人有用。


太好了!正是我遇到的同样问题。 - d9120
1
现在是2016年,你仍然在拯救我们的生命! - Mārtiņš Briedis
为什么要首先实施这个“功能”?它破坏了之前附加到文件输入元素的事件处理程序! - rinogo

3

距离原回答已经两年了,但我刚刚为自己的情况找到了解决方法(:

如果您使用replaceFileInput: false,则该代码将无法在不支持较新文件上传API的IE9中运行。根据文档,此浏览器的回退支持取决于需要每次替换文件输入元素的“iframe传输”。阅读这一点对我来说是很重要的提示。

真正困扰您的是这个:

$(upload_browse).on('click', function () {
  $(upload_file).click();
  return false;
});

您假设upload_file仍然是相同的元素,但它已被替换为克隆。您在旧文件输入元素上触发了点击事件。它存在,因此您会得到系统浏览对话框,但它没有连接到任何管道。
因此,具有完整IE9支持的正确解决方案是每次触发此点击处理程序时使用“find”重新定位upload_file。您没有包括设置upload_file的代码,因此我不知道在您的情况下正确的选择器是什么,但它看起来会像这样:
$(upload_browse).on('click', function () {
  // You should use a more specific selector, better yet use
  // find() to locate it inside some div you know is "in scope" so
  // you don't fire every file input on the page. Just an example
  $('input[type=file]').click();
  return false;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接