在jquery文件上传插件的fileuploadsend事件中检索jqXHR?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在jquery文件上传插件的fileuploadsend事件中检索jqXHR?相关的知识,希望对你有一定的参考价值。

我正在使用拖放来触发我的上传,所以我无法简单地捕获findupload('send')的返回来获取jqXHR。

所以在'fileuploadsend'事件中我试图从数据对象中获取jqXHR元素,但是data.jqXHR似乎是未定义的?

    $('#fileupload')
        .fileupload({
           ...
        }).bind('fileuploadsend', function (e, data) {
            console.log(data)
            console.log(data.jqXHR)
        });

数据对象的输出显示存在jqXHR元素,并且是这样的对象:

jqXHR: Object
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseText: "[{"url": "/media/pictures/392_frm_20130412081933_d3fee37c7a654dfca066ca3fa389b491.jpg", "filename": "waves_1600.jpeg", "sortDate": null, "albumId": 67, "published": false, "source_id": "pfi392", "thumbnailUrl": "/media/cache/a1/c1/a1c1d4f74614cf041b29e315a1f9a08a.jpg", "id": 499}]"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object

但是无论出于何种原因,console.log(data.jqXHR)只是给出了undefined。

如果我运行for (k in data) { console.log(k) },那么列出的jqXHR无处可见:

disabled
create
dropZone
pasteZone
replaceFileInput
singleFileUploads
sequentialUploads
forceIframeTransport
multipart
recalculateProgress
progressInterval
bitrateInterval
formData
add
processData
contentType
cache
url
dataType
fileInput
files
originalFiles
paramName
submit
form
type
formAcceptCharset
uploadedBytes
headers
data
blob
xhr
_bitrateTimer 
答案

我使用了jquery-fileupload的基本加UI版本。

首先,在我的javascript fileupload源代码中粘贴jquery.fileupload.ui.js的一部分。并修改了一些部分。

// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
    url: '/common/fileupload',

    // pasted this part, If the file transfer successful
    // 파일 전송에 성공하면
    done: function (e, data) {
        if (e.isDefaultPrevented()) {
            return false;
        }
        var that = $(this).data('blueimp-fileupload') ||
                $(this).data('fileupload'),
            getFilesFromResponse = data.getFilesFromResponse ||
                that.options.getFilesFromResponse,
            files = getFilesFromResponse(data),
            template,
            deferred;
        if (data.context) {
            data.context.each(function (index) {
                var file = files[index] ||
                        {error: 'Empty file upload result'};
                deferred = that._addFinishedDeferreds();
                that._transition($(this)).done(
                    function () {
                        var node = $(this);
                        template = that._renderDownload([file])
                            .replaceAll(node);
                        that._forceReflow(template);
                        that._transition(template).done(
                            function () {
                                data.context = $(this);
                                that._trigger('completed', e, data);
                                that._trigger('finished', e, data);
                                deferred.resolve();


                                // It succeeded in using jqXHR, I was need of file auto increment id,
                                console.log("fileuploadsuccess", data.jqXHR.responseJSON.files_info[0]);
                                // and I called custom callback function.
                                fn_file_callback("fileuploadsuccess", e, data.jqXHR.responseJSON.files_info[0]);
                            }
                        );
                    }
                );
            });
        } else {
            template = that._renderDownload(files)[
                that.options.prependFiles ? 'prependTo' : 'appendTo'
            ](that.options.filesContainer);
            that._forceReflow(template);
            deferred = that._addFinishedDeferreds();
            that._transition(template).done(
                function () {
                    data.context = $(this);
                    that._trigger('completed', e, data);
                    that._trigger('finished', e, data);
                    deferred.resolve();
                }
            );
        }
    },

    // then pasted this part.. If the file remove done.
    // 파일을 삭제하면
    destroy: function (e, data) {
        if (e.isDefaultPrevented()) {
            return false;
        }
        var that = $(this).data('blueimp-fileupload') ||
                $(this).data('fileupload'),
            removeNode = function () {
                that._transition(data.context).done(
                    function () {
                        $(this).remove();
                        that._trigger('destroyed', e, data);

                        // add here, I called custom callback function about file deletion.
                        fn_file_callback("filedeletesuccess", e, data.url.replace("/common/deleteFile/", ""));
                    }
                );
            };
        if (data.url) {
            data.dataType = data.dataType || that.options.dataType;
            $.ajax(data).done(removeNode).fail(function () {
                that._trigger('destroyfailed', e, data);
            });
        } else {
            removeNode();
        }
    }
});

从这里休息。

// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
    'option',
    'redirect',
    window.location.href.replace(
        //[^/]*$/,
        '/cors/result.html?%s'
    )
);

if (window.location.hostname === 'localhost:8080') {
    // Demo settings:
    $('#fileupload').fileupload('option', {
        url: '/common/fileupload',
        disableImageResize: /android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        maxFileSize: 999000,
        acceptFileTypes: /(.|/)(gif|jpe?g|png)$/i
    });
    // Upload server status check for browsers with CORS support:
    if ($.support.cors) {
        $.ajax({
            url: '/common/fileupload',
            type: 'HEAD'
        }).fail(function () {
            $('<div class="alert alert-danger"/>')
                .text('Upload server currently unavailable - ' +
                        new Date())
                .appendTo('#fileupload');
        });
    }
} else {
    // Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: $('#fileupload').fileupload('option', 'url'),
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
            .call(this, $.Event('done'), {result: result});
    });
}

祝你好运!

以上是关于在jquery文件上传插件的fileuploadsend事件中检索jqXHR?的主要内容,如果未能解决你的问题,请参考以下文章

jQuery FileUpload 插件[转]

在jquery文件上传插件的fileuploadsend事件中检索jqXHR?

使用 jQuery FileUpload 插件实现异步上传

jquery文件上传进度条不准确

jQuery fileupload 多文件上传

在admui中怎样上传本地文件?