[ Поиск ] - [ Пользователи ] - [ Календарь ]
Полная Версия: jquery + file API
Invis1ble
Наткнулся на странный баг, имеется коллекция объектов jQuery. Перебираю их в цикле
            fields.each(function()
{
if ($(this).attr('type') == 'file' && $(this).attr('accept') !== undefined &&
self.form.attr('enctype') === 'multipart/form-data'
) {
try {
var file = $(this).attr('files')[0]; // баг
// code

}
catch (e) { }
}

// code
});

на строке с комментом "баг" происходит какая-то мистика:
дебаг (Watch Expressions) показывает, что в $(this) есть, как и положено HTMLInputElement, у которого в свою очередь есть свойство files - ну и там вся нужная мне инфа. Однако, при обращении из скрипта $(this).files выдает undefined. Ну и самое смешное, что если вместо $(this).attr('files') написать костыль вида document.getElementById($(this).attr('id')).files - получаем FileList :)
Вот такие пироги. Проверял в GoogleChromium 15 и Opera 11.51 - результат идентичный, в FF не проверил, т.к. он у меня что-то глючит.
У кого какие есть мысли по этому поводу? Может у меня ошибка в скрипте, а я как истинный нуб сваливаю вину на других? :)



Спустя 3 часа, 22 минуты, 38 секунд (11.11.2011 - 19:28) redreem написал(а):
знакомая ситуация. селектор jQuery далеко не всегда возвращает истинно DOM-объект. чаще всего это внутренний объект jQuery.

Спустя 16 минут, 5 секунд (11.11.2011 - 19:44) sharki написал(а):
А если
var file = $(this).attr('files').eq(0); // баг

Спустя 1 час, 52 минуты, 40 секунд (11.11.2011 - 21:37) alex12060 написал(а):
Invis1ble

ЖК не любит обращения, вида [0]

Попробуй либо как шарки написал, если не ахти, попробуй так:


$(this).attr('files').val();

Спустя 1 час, 21 минута, 50 секунд (11.11.2011 - 22:58) Invis1ble написал(а):
sharki
Цитата
var file = $(this).attr('files').eq(0);

alex12060
Цитата
ЖК не любит обращения, вида [0]

индекс тут непричем, самого массива якобы не существует - undefined, хотя если дампнуть (GC - Watch Expressions, Opera - отслеживание) $(this) - показывает, что этот массив есть smile.gif

PS.
дамп
Цитата
    $(this): e.fn.e.init[1]
        0: HTMLInputElement
            accept: "image/jpeg,image/png,image/gif"
            accessKey: ""
            align: ""
            alt: ""
            attributes: NamedNodeMap
            autocomplete: ""
            autofocus: false
            baseURI: "http://jambo/registration"
            checked: false
            childElementCount: 0
            childNodes: NodeList[0]
            children: HTMLCollection[0]
            classList: DOMTokenList
            className: "photo"
            clientHeight: 21
            clientLeft: 0
            clientTop: 0
            clientWidth: 238
            contentEditable: "inherit"
            dataset: DOMStringMap
            defaultChecked: false
            defaultValue: ""
            dir: ""
            disabled: false
            draggable: false
            files: FileList
                0: File
                    fileName: "class.upload.php"
                    fileSize: 265209
                    lastModifiedDate: Date
                    name: "class.upload.php"
                    size: 265209
                    type: "application/x-php"
                    webkitRelativePath: ""
                    __proto__: File
                length: 1
                __proto__: FileList

            firstChild: null
            firstElementChild: null
            form: HTMLFormElement
            formAction: ""
            formEnctype: ""
            formMethod: ""
            formNoValidate: false
            formTarget: ""
            hidden: false
            id: "photo"
            incremental: false
            indeterminate: false
            innerHTML: ""
            innerText: ""
            isContentEditable: false
            labels: NodeList[1]
            lang: ""
            lastChild: null
            lastElementChild: null
            localName: "input"
            max: ""
            maxLength: 524288
            min: ""
            multiple: false
            name: "photo"
            namespaceURI: "http://www.w3.org/1999/xhtml"
            nextElementSibling: null
            nextSibling: Text
            nodeName: "INPUT"
            nodeType: 1
            nodeValue: null
            offsetHeight: 21
            offsetLeft: 407
            offsetParent: HTMLBodyElement
            offsetTop: 629
            offsetWidth: 238
            onabort: null
            onbeforecopy: null
            onbeforecut: null
            onbeforepaste: null
            onblur: null
            onchange: null
            onclick: null
            oncontextmenu: null
            oncopy: null
            oncut: null
            ondblclick: null
            ondrag: null
            ondragend: null
            ondragenter: null
            ondragleave: null
            ondragover: null
            ondragstart: null
            ondrop: null
            onerror: null
            onfocus: null
            oninput: null
            oninvalid: null
            onkeydown: null
            onkeypress: null
            onkeyup: null
            onload: null
            onmousedown: null
            onmousemove: null
            onmouseout: null
            onmouseover: null
            onmouseup: null
            onmousewheel: null
            onpaste: null
            onreset: null
            onscroll: null
            onsearch: null
            onselect: null
            onselectstart: null
            onsubmit: null
            onwebkitfullscreenchange: null
            onwebkitspeechchange: null
            outerHTML: "<input type="file" id="photo" name="photo" accept="image/jpeg,image/png,image/gif" class="photo">"
            outerText: ""
            ownerDocument: HTMLDocument
            parentElement: HTMLElement
            parentNode: HTMLElement
            pattern: ""
            placeholder: ""
            prefix: null
            previousElementSibling: HTMLInputElement
            previousSibling: Text
            readOnly: false
            required: false
            scrollHeight: 21
            scrollLeft: 0
            scrollTop: 0
            scrollWidth: 238
            selectionDirection: [Exception: TypeError]
            selectionEnd: [Exception: TypeError]
            selectionStart: [Exception: TypeError]
            size: 20
            spellcheck: true
            src: ""
            step: ""
            style: CSSStyleDeclaration
            tabIndex: 0
            tagName: "INPUT"
            textContent: ""
            title: ""
            type: "file"
            useMap: ""
            validationMessage: ""
            validity: ValidityState
            value: "C:\fakepath\class.upload.php"
            valueAsDate: null
            valueAsNumber: NaN
            webkitGrammar: false
            webkitSpeech: false
            webkitdirectory: false
            webkitdropzone: ""
            willValidate: true
        __proto__: HTMLInputElement
            context: HTMLInputElement
            accept: "image/jpeg,image/png,image/gif"
            accessKey: ""
            align: ""
            alt: ""
            attributes: NamedNodeMap
            autocomplete: ""
            autofocus: false
            baseURI: "http://jambo/registration"
            checked: false
            childElementCount: 0
            childNodes: NodeList[0]
            children: HTMLCollection[0]
            classList: DOMTokenList
            className: "photo"
            clientHeight: 21
            clientLeft: 0
            clientTop: 0
            clientWidth: 238
            contentEditable: "inherit"
            dataset: DOMStringMap
            defaultChecked: false
            defaultValue: ""
            dir: ""
            disabled: false
            draggable: false
            files: FileList
                0: File
                    fileName: "class.upload.php"
                    fileSize: 265209
                    lastModifiedDate: Date
                    name: "class.upload.php"
                    size: 265209
                    type: "application/x-php"
                    webkitRelativePath: ""
                    __proto__: File
                length: 1
                __proto__: FileList

            firstChild: null
            firstElementChild: null
            form: HTMLFormElement
            formAction: ""
            formEnctype: ""
            formMethod: ""
            formNoValidate: false
            formTarget: ""
            hidden: false
            id: "photo"
            incremental: false
            indeterminate: false
            innerHTML: ""
            innerText: ""
            isContentEditable: false
            labels: NodeList[1]
            lang: ""
            lastChild: null
            lastElementChild: null
            localName: "input"
            max: ""
            maxLength: 524288
            min: ""
            multiple: false
            name: "photo"
            namespaceURI: "http://www.w3.org/1999/xhtml"
            nextElementSibling: null
            nextSibling: Text
            nodeName: "INPUT"
            nodeType: 1
            nodeValue: null
            offsetHeight: 21
            offsetLeft: 407
            offsetParent: HTMLBodyElement
            offsetTop: 629
            offsetWidth: 238
            onabort: null
            onbeforecopy: null
            onbeforecut: null
            onbeforepaste: null
            onblur: null
            onchange: null
            onclick: null
            oncontextmenu: null
            oncopy: null
            oncut: null
            ondblclick: null
            ondrag: null
            ondragend: null
            ondragenter: null
            ondragleave: null
            ondragover: null
            ondragstart: null
            ondrop: null
            onerror: null
            onfocus: null
            oninput: null
            oninvalid: null
            onkeydown: null
            onkeypress: null
            onkeyup: null
            onload: null
            onmousedown: null
            onmousemove: null
            onmouseout: null
            onmouseover: null
            onmouseup: null
            onmousewheel: null
            onpaste: null
            onreset: null
            onscroll: null
            onsearch: null
            onselect: null
            onselectstart: null
            onsubmit: null
            onwebkitfullscreenchange: null
            onwebkitspeechchange: null
            outerHTML: "<input type="file" id="photo" name="photo" accept="image/jpeg,image/png,image/gif" class="photo">"
            outerText: ""
            ownerDocument: HTMLDocument
            parentElement: HTMLElement
            parentNode: HTMLElement
            pattern: ""
            placeholder: ""
            prefix: null
            previousElementSibling: HTMLInputElement
            previousSibling: Text
            readOnly: false
            required: false
            scrollHeight: 21
            scrollLeft: 0
            scrollTop: 0
            scrollWidth: 238
            selectionDirection: [Exception: TypeError]
            selectionEnd: [Exception: TypeError]
            selectionStart: [Exception: TypeError]
            size: 20
            spellcheck: true
            src: ""
            step: ""
            style: CSSStyleDeclaration
            tabIndex: 0
            tagName: "INPUT"
            textContent: ""
            title: ""
            type: "file"
            useMap: ""
            validationMessage: ""
            validity: ValidityState
            value: "C:\fakepath\class.upload.php"
            valueAsDate: null
            valueAsNumber: NaN
            webkitGrammar: false
            webkitSpeech: false
            webkitdirectory: false
            webkitdropzone: ""
            willValidate: true
            __proto__: HTMLInputElement
        length: 1
        __proto__: Object[0]
    $(this).attr('files')[0]: [Exception: TypeError: Cannot read property '0' of undefined]
    $(this).attr('files').eq(0): [Exception: TypeError: Cannot call method 'eq' of undefined]
    $(this).attr('files').val(): [Exception: TypeError: Cannot call method 'val' of undefined]
    $(this).attr('files').item(0): [Exception: TypeError: Cannot call method 'item' of undefined]
    $(this).attr('files'): undefined

Спустя 1 час, 39 минут, 39 секунд (12.11.2011 - 00:38) Greg1978 написал(а):
возможно вот так, иногда это и есть объект но его нужно инициализировать в jquery:
var file = $(this).attr('files');
$(file[0]).

Спустя 21 минута, 13 секунд (12.11.2011 - 00:59) Invis1ble написал(а):
Greg1978
результат тот же

ПС. В скрине выше у меня опечатка в коде, вместо
var file = $(this).files.eq(0)

там стояло
var file = $(this).attr('files').eq(0)

просто скрин позже сделал, чем дамп

Спустя 16 минут, 21 секунда (12.11.2011 - 01:16) Greg1978 написал(а):
Так, а this - дамп его могли бы показать. Что то мне подсказывает что здесь не стоит применять обёртку jquery а на прямую работать с объектом:
this.files или с jquery но доступ к свойству но не к атрибуту. Атрибут возвращает строковый литерал, как мне помнится.

Спустя 7 минут, 49 секунд (12.11.2011 - 01:23) Invis1ble написал(а):
this
Цитата
Local
    .......
    this: HTMLInputElement
        accept: "image/jpeg,image/png,image/gif"
        accessKey: ""
        align: ""
        alt: ""
        attributes: NamedNodeMap
        autocomplete: ""
        autofocus: false
        baseURI: "http://jambo/registration"
        checked: false
        childElementCount: 0
        childNodes: NodeList[0]
        children: HTMLCollection[0]
        classList: DOMTokenList
        className: "photo"
        clientHeight: 21
        clientLeft: 0
        clientTop: 0
        clientWidth: 238
        contentEditable: "inherit"
        dataset: DOMStringMap
        defaultChecked: false
        defaultValue: ""
        dir: ""
        disabled: false
        draggable: false
        files: FileList
            0: File
                fileName: "class.upload.php"
                fileSize: 265209
                lastModifiedDate: Date
                name: "class.upload.php"
                size: 265209
                type: "application/x-php"
                webkitRelativePath: ""
                __proto__: File
            length: 1
            __proto__: FileList

        firstChild: null
        firstElementChild: null
        form: HTMLFormElement
        formAction: ""
        formEnctype: ""
        formMethod: ""
        formNoValidate: false
        formTarget: ""
        hidden: false
        id: "photo"
        incremental: false
        indeterminate: false
        innerHTML: ""
        innerText: ""
        isContentEditable: false
        labels: NodeList[1]
        lang: ""
        lastChild: null
        lastElementChild: null
        localName: "input"
        max: ""
        maxLength: 524288
        min: ""
        multiple: false
        name: "photo"
        namespaceURI: "http://www.w3.org/1999/xhtml"
        nextElementSibling: null
        nextSibling: Text
        nodeName: "INPUT"
        nodeType: 1
        nodeValue: null
        offsetHeight: 21
        offsetLeft: 407
        offsetParent: HTMLBodyElement
        offsetTop: 629
        offsetWidth: 238
        onabort: null
        onbeforecopy: null
        onbeforecut: null
        onbeforepaste: null
        onblur: null
        onchange: null
        onclick: null
        oncontextmenu: null
        oncopy: null
        oncut: null
        ondblclick: null
        ondrag: null
        ondragend: null
        ondragenter: null
        ondragleave: null
        ondragover: null
        ondragstart: null
        ondrop: null
        onerror: null
        onfocus: null
        oninput: null
        oninvalid: null
        onkeydown: null
        onkeypress: null
        onkeyup: null
        onload: null
        onmousedown: null
        onmousemove: null
        onmouseout: null
        onmouseover: null
        onmouseup: null
        onmousewheel: null
        onpaste: null
        onreset: null
        onscroll: null
        onsearch: null
        onselect: null
        onselectstart: null
        onsubmit: null
        onwebkitfullscreenchange: null
        onwebkitspeechchange: null
        outerHTML: "<input type="file" id="photo" name="photo" accept="image/jpeg,image/png,image/gif" class="photo">"
        outerText: ""
        ownerDocument: HTMLDocument
        parentElement: HTMLElement
        parentNode: HTMLElement
        pattern: ""
        placeholder: ""
        prefix: null
        previousElementSibling: HTMLInputElement
        previousSibling: Text
        readOnly: false
        required: false
        scrollHeight: 21
        scrollLeft: 0
        scrollTop: 0
        scrollWidth: 238
        selectionDirection: [Exception: TypeError]
        selectionEnd: [Exception: TypeError]
        selectionStart: [Exception: TypeError]
        size: 20
        spellcheck: true
        src: ""
        step: ""
        style: CSSStyleDeclaration
        tabIndex: 0
        tagName: "INPUT"
        textContent: ""
        title: ""
        type: "file"
        useMap: ""
        validationMessage: ""
        validity: ValidityState
        value: "C:\fakepath\class.upload.php"
        valueAsDate: null
        valueAsNumber: NaN
        webkitGrammar: false
        webkitSpeech: false
        webkitdirectory: false
        webkitdropzone: ""
        willValidate: true
        __proto__: HTMLInputElement


> var file = $(this).attr('files')[0]; - breakpoint



Спустя 6 минут, 28 секунд Invis1ble написал(а):
Greg1978
Цитата
Атрибут возвращает строковый литерал, как мне помнится.

другой аналогичный скрипт работает нормально (с аналогичной формой и данным куском кода), т.е. $(this).attr('files')[0] возвращает File

Спустя 8 минут, 19 секунд (12.11.2011 - 01:32) Greg1978 написал(а):
Вот, скорее всего это тот случай, я делал маленькую библиотеку по работе с DOM наподобие jquery, бывали случаи в том что при возврате из функций происходили не сами объекты DOM как сказал redreem а объект самой моей библиотеки. Сейчас если хотите посмотрите дамп вот этой конструкции:
this.files, если не напряг конечно smile.gif

Спустя 9 минут, 27 секунд (12.11.2011 - 01:41) Invis1ble написал(а):
да, уже проверил. Без jquery-обёртки все нормально.
this.files[0] возвращает File smile.gif

Спустя 6 минут, 58 секунд (12.11.2011 - 01:48) Greg1978 написал(а):
Цитата (Invis1ble @ 11.11.2011 - 22:41)
да, уже проверил. Без jquery-обёртки все нормально.
this.files[0] возвращает File smile.gif

у меня на этот случай всегда есть функция $('element').getElement(); возвращает сам DOM элемент - может и в jquery есть то же

Спустя 7 часов, 48 минут, 27 секунд (12.11.2011 - 09:37) Michael написал(а):
Цитата (Invis1ble)
var file = $(this).attr('files')[0]; // баг

files - это не атрибут, а свойство
Надо:
$(this)[0].files

или просто this.files

Спустя 1 день, 13 часов, 47 минут, 46 секунд (13.11.2011 - 23:24) Invis1ble написал(а):
Michael
точно, спасибо


_____________

Профессиональная разработка на заказ

Я на GitHub | второй профиль

Быстрый ответ:

 Графические смайлики |  Показывать подпись
Здесь расположена полная версия этой страницы.
Invision Power Board © 2001-2024 Invision Power Services, Inc.