JQuery-UI对话框小部件和Fine-Uploader上传

时间:2013-08-16 16:20:56

标签: jquery-ui asp.net-mvc-4 fine-uploader

我在尝试上传时遇到此问题。未到达FineUploader实例的请求端点中配置的URL。 我使用的是FineUploader v3.7.1和JQuery-UI v1.10.3。 以下是我的代码:

SCRIPT

$(document).ready(function () {

        $(function () {
            $('#dialog').dialog({
                autoOpen: false,
                width: 400,
                height: 500,
                resizable: false,
                modal: true,
                draggable: false,
                buttons: [
                    {
                        text: "Aceptar",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });
        });

        $('#upload').fineUploader({
            text: {
                uploadButton: 'Agregar imágen al evento',
                deleteButton: 'Eliminar imagen'
            },
            // template for one item in file list
            fileTemplate:
                '<span>' +
                '<div class="qq-progress-bar"></div>' +
                '<span class="qq-upload-spinner"></span>' +
                '<span class="qq-upload-finished"></span>' +
                '<span class="qq-upload-file"></span>' +
                '<span class="qq-upload-size"></span>' +
                '<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
                '<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
                '<a class="qq-upload-delete" href="#">{deleteButtonText}</a>' +
                '<span class="qq-upload-status-text">{statusText}</span>' +
                '</span>',
            classes: {
            },
            request: {
                endpoint: '<%= Url.Action("UploadNewDesign", "Account") %>'
            },
            deleteFile: {
                enabled: true,
                endpoint: '<%= Url.Action("DeleteNewDesign", "Account") %>',
                method: 'POST'
            },
            multiple: true,
            validation: {

            },
            showMessage: function (message) {

            },
            messages: {

            }
        })
        .on('submit', function (event, id, name) {

        })
        .on('submitted', function (event, id, name) {
            var fileItemContainer = $(this).fineUploader('getItemByFileId', id);

            $('#dialog').html(fileItemContainer);
            $("#dialog").dialog("open");
        })
        .on('complete', function (event, id, fileName, responseJSON) {
            if (responseJSON.success) {

            }
        })
        .on('submitDelete', function (event, id) {

        })
        .on('deleteComplete', function (event, id, xhrOrXdr, isError) {
            if (!isError) {

            }
        });
    })

HTML

<div id="upload"></div>
<div id="dialog"></div>

仅当我将fileTemplate html(调用FineUploader API)放在JQuery Dialog Widget上时才会发生这种情况。如果我尝试将fileTemplate html放在视图内的元素中,则会到达Action Controller。

更新

下面如果我的更新代码,我正在复制fileTemplate的DOM

SCRIPT

$('#upload').fineUploader({
            text: {
                uploadButton: 'Agregar imágen al evento',
                deleteButton: 'Eliminar imagen'
            },
            listElement: $('#dialog')[0],
            fileTemplate:
                '<span>' +
                '<div class="qq-progress-bar"></div>' +
                '<span class="qq-upload-spinner"></span>' +
                '<span class="qq-upload-finished"></span>' +
                '<span class="qq-upload-file"></span>' +
                '<span class="qq-upload-size"></span>' +
                '<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
                '<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
                '<a class="qq-upload-delete" href="#">{deleteButtonText}</a>' +
                '<span class="qq-upload-status-text">{statusText}</span>' +
                '</span>',
            classes: {
            },
            request: {
                endpoint: '<%= Url.Action("UploadNewDesign", "Account") %>'
            },
            deleteFile: {
                enabled: true,
                endpoint: '<%= Url.Action("DeleteNewDesign", "Account") %>',
                method: 'POST'
            },
            validation: {
                allowedExtensions: ['png'],
                sizeLimit: 411062 // 50 kB = 50 * 1024 bytes
            },
            multiple: true,
            showMessage: function (message) {
                $('#dialog').html(message);
                $("#dialog").dialog("open");
            },
            messages: {

            }
        })
        .on('submit', function (event, id, name) {

        })
        .on('submitted', function (event, id, name) {
            var fileItemContainer = $(this).fineUploader('getItemByFileId', id);

            $('#dialog').html(fileItemContainer);
            $("#dialog").dialog("open");
        })
        .on('complete', function (event, id, fileName, responseJSON) {
            if (responseJSON.success) {
                var fileName = $(this).fineUploader('getName', id);
                $('#tblFiles > tbody:last').append('<tr><td>' + fileName + '</td></tr>');
            }
        })
        .on('submitDelete', function (event, id) {

        })
        .on('deleteComplete', function (event, id, xhrOrXdr, isError) {
            if (!isError) {

            }
        });
    })

HTML

<div id="upload"></div>
<div id="dialog"></div>

<table id="tblFiles">
    <tbody></tbody>
</table>

更新

我成功地做了我想做的事。请看一看并告诉我这是否是一种更好的方式来做我做的事情。下面有一些图片(OHH STACKOVERFLOW不允许我,因为我没有足够的声誉,我结束了删除所有这些),解释我在搜索什么

最后代码更新了,如果有更好的方法,请告诉我

$('#FileTemplate').dialog({
            //dialogClass: "no-dialog-titlebar-close",
            autoOpen: false,
            width: 400,
            height: "auto",
            resizable: false,
            modal: true,
            draggable: false,
            buttons: [
                {
                    text: "Aceptar",
                    click: function () {

                        $(this).dialog("close");
                    }
                }
            ]
        });

        $(".ui-dialog-titlebar").hide();

        $('#Messages').dialog({
            autoOpen: false,
            width: "auto",
            height: "auto",
            resizable: false,
            modal: true,
            draggable: false,
            buttons: [
                {
                    text: "Aceptar",
                    click: function () {

                        $(this).dialog("close");
                    }
                }
            ]
        }); 

        $('#Upload').fineUploader({
            messages: {
                typeError: "{file} tiene una extension inválida. Las extensiones validas son: {extensions}.",
                sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
                minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
                emptyError: "{file} is empty, please select files again without it.",
                noFilesError: "No files to upload.",
                tooManyItemsError: "Too many items ({netItems}) would be uploaded.  Item limit is {itemLimit}.",
                retryFailTooManyItems: "Retry failed - you have reached your file limit.",
                onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
            },
            text: {
                uploadButton: 'Agregar imágen al evento',
                deleteButton: 'Eliminar imagen',
                cancelButton: 'Cancel',
                retryButton: 'Retry',
                failUpload: 'Upload failed',
                formatProgress: "{percent}% de {total_size}",
                waitingForResponse: "Procesando..."
            },
            template: '<div class="qq-uploader">' +
                '<div class="qq-upload-drop-area"><span>{dragZoneText}</span></div>' +
                '<div class="div-button-style"><div>{uploadButtonText}</div></div>' +
                '<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
                '</div>',
            listElement: $("#FileTemplate"),
            fileTemplate:
                '<span>' +
                    '<div class="qq-progress-bar"></div>' +
                    '<span class="qq-upload-spinner"></span>' +
                    '<span class="qq-upload-finished"></span>' +
                    '<span class="qq-upload-file"></span>' +
                    '<span class="qq-upload-size"></span>' +
                    '<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
                    '<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
                    '<a class="qq-upload-delete-hide" href="#">{deleteButtonText}</a>' +
                    '<span class="qq-upload-status-text">{statusText}</span>' +
                '</span>',
            classes: {
                deleteButton: "qq-upload-delete-hide",
                button: "div-button-style"
            },
            request: {
                endpoint: '<%= Url.Action("UploadNewDesign", "Account") %>'
            },
            deleteFile: {
                enabled: true,
                endpoint: '<%= Url.Action("DeleteNewDesign", "Account") %>',
                method: 'POST'
            },
            validation: {
                allowedExtensions: ['png'],
                sizeLimit: 411062 // 50 kB = 50 * 1024 bytes
            },
            multiple: true,
            showMessage: function (message) {
                $('#Messages').html(message);
                $("#Messages").dialog("open");
            }
        })
        .on('submitted', function (event, id, name) {

            var files = $('#Upload').fineUploader('getUploads');
            // SPECIALLY IN THIS PART, WHERE I'M HIDING ALL THE OTHERS FILETEMPLATES
            $.each(files, function (index, value) {
                var exists = $('#Upload').fineUploader('doesExist', value.id);

                if (exists && value.id != id)
                    $('#Upload').fineUploader('getItemByFileId', value.id).hide(); 
            });

            $("#FileTemplate").dialog("open");
        })
        .on('complete', function (event, id, fileName, responseJSON) {
            if (responseJSON.success) {
                var fileName = $(this).fineUploader('getName', id);
                $('#tblFiles > tbody:last').append(
                    '<tr>' +
                        '<td class="hide-element"><input type="hidden" value="' + responseJSON.filename + '"/></td>' +
                        '<td class="hide-element"><input type="hidden" value="' + id + '"/></td>' +
                        '<td>' +
                            '<div class="pointer-cursor" title="Eliminar imagen" onclick="DeleteImage(' + id + ')">' +
                                '<image src="/Images/trash.png" />' +
                            '</div>' +
                        '</td>' +
                        '<td onclick="SelectImage(' + id + ')" class="pointer-cursor">' + fileName + '</td>' +
                    '</tr>');

                SelectImage(id);

                return;
            }

            $('#Messages').html("Se produjo un error al subir el archivo");
            $("#Messages").dialog("open");
        })
        .on('submitDelete', function (event, id) {
            $(this).fineUploader('setDeleteFileParams', { filename: $(this).fineUploader('getName', id)}, id);
        })
        .on('deleteComplete', function (event, id, xhrOrXdr, isError) {
            if (!isError) {

                var trIndex;
                var trRemoved = false;
                var firstFileId;

                for (trIndex = 0; trIndex < $('#tblFiles tbody tr').length && !trRemoved; trIndex++) {
                    var fileId = $($('#tblFiles tbody tr')[trIndex]).find('td input')[1].value;

                    if (!firstFileId)
                        firstFileId = fileId;

                    // Remove the tr associated with file
                    if (fileId == id) {
                        $($('#tblFiles tbody tr')[trIndex]).remove();
                        trRemoved = true;
                    }
                }

                if ($('#tblFiles tbody tr').length == 0) {
                    // No images left
                    $("#imgUploaded").attr("src", "/Images/no_image_mid.png");
                    $("#IdImageSelected").val("");
                }
                else {
                    // If the image was the selected, selected another
                    if ($("#IdImageSelected").val() == id)
                        SelectImage(firstFileId);
                }

                return;
            }

            $('#Messages').html("Se produjo un error al querer eliminar el archivo");
            $("#Messages").dialog("open");
        });

    })

    function DeleteImage(id) {
        $('#Upload').fineUploader('deleteFile', id);
    }

    function SelectImage(id) {

        $('#tblFiles tbody tr').each(function () {

            var fileId = $(this).find('td input')[1].value;
            // FileName on server
            var fileName = $(this).find('td input')[0].value;

            var row = $(this).children();

            if (fileId == id) {
                // Assign the selected style
                row.addClass("image-selected");

                $("#imgUploaded").attr("src", "<%: _imagesDirectory %>/" + fileName);
                $("#IdImageSelected").val(id);
            }
            else {
                row.removeClass("image-selected");
            }
        });
    }

HTML

<table>
    <tbody>
        <tr>
            <td>
                <img id="imgUploaded" src="/Images/no_image_mid.png"  style="width:200px; height:200px" />
                <input type="hidden" class="hide-element" id="IdImageSelected"/>
            </td>
        </tr>
        <tr>
            <td>
                <div id="Upload"></div>
            </td>
        </tr>
    </tbody>
</table>

<div id="FileTemplate"></div>
<div id="Messages" title="Error"></div>

<table id="tblFiles">
    <tbody></tbody>
</table>

我希望你明白我要做的事情

1 个答案:

答案 0 :(得分:0)

我的代码仍然有些困惑。我会尽力回答您的问题,但如果您只是提供一个包含您在问题中列出的代码的工作版本的页面的链接,那么我将更容易帮助您。 / p>

Fine Uploader将在#dialog中创建文件项,因为您已将#dialog设置为listElement。根据您的评论,这似乎就是您想要做的。但是,每次在submitted处理程序中提交文件时,您都会替换#dialog的全部内容。为什么?我猜你真的不想这样做。你应该再看看documentation for jQuery's html function

您还在showMessage实施中使用来自Fine Uploader的消息覆盖同一#dialog的内容(再次)。再说一次,我相信你也不想这样做。如果你想在自定义对话框中显示这些消息,那么你应该选择一个新的对话框,而不是那个持有上传者HTML的对话框。

我可以建议您删除submitted处理程序和showMessage实现,因为您添加到这两部分的代码没有任何意义。

另外,你有很多空选项。如果您因某些原因遗漏了部分代码,我不确定您是否理解这些工作原理。

最后,您可以传入#dialog的jQuery对象,因为您正在使用Fine Uploader jQuery包装器。您的listElement选项的值可以为$('dialog')