parsing a formdata object with javascript

后端 未结 2 478
逝去的感伤
逝去的感伤 2020-12-21 19:03

My company uses a propitiatory application server in which the server side programs are written in javascript (not node.js) . This is a very initial thing and support isn\'t

2条回答
  •  醉话见心
    2020-12-21 19:13

    Best would be to use node-formidable, browserify and polyfill it. Here is a standalone parser, works both with string and raw responses. Make sure you use a modern browser for the raw-stuff.

    /* 
     * MultiPart_parse decodes a multipart/form-data encoded response into a named-part-map.
     * The response can be a string or raw bytes.
     *
     * Usage for string response:
     *      var map = MultiPart_parse(xhr.responseText, xhr.getResponseHeader('Content-Type'));
     *
     * Usage for raw bytes:
     *      xhr.open(..);     
     *      xhr.responseType = "arraybuffer";
     *      ...
     *      var map = MultiPart_parse(xhr.response, xhr.getResponseHeader('Content-Type'));
     *
     * TODO: Can we use https://github.com/felixge/node-formidable
     * See http://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers
     * See http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
     *
     * Copyright@ 2013-2014 Wolfgang Kuehn, released under the MIT license.
    */
    function MultiPart_parse(body, contentType) {
        // Examples for content types:
        //      multipart/form-data; boundary="----7dd322351017c"; ...
        //      multipart/form-data; boundary=----7dd322351017c; ...
        var m = contentType.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
    
        if ( !m ) {
            throw new Error('Bad content-type header, no multipart boundary');
        }
    
        var boundary = m[1] || m[2];
    
        function Header_parse(header) {
            var headerFields = {};
            var matchResult = header.match(/^.*name="([^"]*)"$/);
            if ( matchResult ) headerFields.name = matchResult[1];
            return headerFields;
        }
    
        function rawStringToBuffer( str ) {
            var idx, len = str.length, arr = new Array( len );
            for ( idx = 0 ; idx < len ; ++idx ) {
                arr[ idx ] = str.charCodeAt(idx) & 0xFF;
            }
            return new Uint8Array( arr ).buffer;
        }
    
        // \r\n is part of the boundary.
        var boundary = '\r\n--' + boundary;
    
        var isRaw = typeof(body) !== 'string';
    
        if ( isRaw ) {
            var view = new Uint8Array( body );
            s = String.fromCharCode.apply(null, view);
        } else {
            s = body;
        }
    
        // Prepend what has been stripped by the body parsing mechanism.
        s = '\r\n' + s;
    
        var parts = s.split(new RegExp(boundary)),
            partsByName = {};
    
        // First part is a preamble, last part is closing '--'
        for (var i=1; i

提交回复
热议问题