How do I serialize file type input in jquery

前端 未结 5 975
遥遥无期
遥遥无期 2020-12-31 10:04

Previously using Prototype I could serialize the input type file, it gave me the file name of the file being uploaded but when I serialized the form in jquery I just got the

5条回答
  •  长发绾君心
    2020-12-31 10:38

    Relevant jQuery bug: http://bugs.jquery.com/ticket/2656

    I added my own serializeAll method instead of serialize:

        (function($) { 
        $.fn.serializeAll = function() {
            var rselectTextarea = /^(?:select|textarea)/i;
            var rinput = /^(?:color|date|datetime|datetime-local|email|file|hidden|month|number|password|range|search|tel|text|time|url|week)$/i;
            var rCRLF = /\r?\n/g;
    
            var arr = this.map(function(){
                return this.elements ? jQuery.makeArray( this.elements ) : this;
            })
            .filter(function(){
                return this.name && !this.disabled &&
                    ( this.checked || rselectTextarea.test( this.nodeName ) ||
                        rinput.test( this.type ) );
            })
            .map(function( i, elem ){
                var val = jQuery( this ).val();
    
                return val == null ?
                    null :
                    jQuery.isArray( val ) ?
                        jQuery.map( val, function( val, i ){
                            return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                        }) :
                        { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
            }).get();
    
            return $.param(arr);
        }
    })(jQuery);
    

    Then call:

    $('#form').serializeAll()
    

提交回复
热议问题