如何手动创建multipart / form-data

时间:2017-11-02 17:04:19

标签: javascript multipartform-data

2 个答案:

答案 0 :(得分:5)

您可以使用XMLHttpRequest手动创建multipart/form-data,例如此示例。

function multiPost(method, url, formHash){
    var boundary = "nVenJ7H4puv"
    var body = ""
    for(var key in formHash){
        body += "--" + boundary
             + "\r\nContent-Disposition: form-data; name=" + formHash[key].name
             + "\r\nContent-type: " + formHash[key].type
             + "\r\n\r\n" + formHash[key].value + "\r\n"
    }
    body += "--" + boundary + "--\r\n"

    var xml = new XMLHttpRequest();
    xml.open(method, url)
    xml.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary)
    xml.setRequestHeader("Content-Length", body.length)
    xml.send(body)
}

答案 1 :(得分:2)

您可以编写自己的FormData polyfill,或只是谷歌“FormData polyfill”)))并且您还可以在浏览器Chrome,FireFox,Opera,Safari,IE(10 +),Edge使用普通FormData。 FormData polyfill仅对旧IE和工人有用,但对于工人,最好使用它 - https://gist.github.com/Rob--W/8b5adedd84c0d36aba64

wikipedia

standart formdata not of body

你需要做什么?您想发送formdata还是在js收到它?

您可以尝试使用我的polyfill,但我还没有测试过它。

示例:

var data = new RawFormData();
data.append("key","value")
data.append("key", new Blob("test"), "my file.txt");
data.getOutputDeferred().then(function(formData){
    var xml = new XMLHttpRequest();
    xml.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.getBoundry());
    xml.setRequestHeader("Content-Length", formData.length);
    xml.open(method, url);
    xml.send(formData);
});

代码:

/**
* @constructor
*/
RawFormData = function () {
    this._promises = [];
    this._boundry = this.makeBoundary();
};

/**
* @return {string}
*/
RawFormData.prototype.getBoundary = function () {
    return this._boundry;
}

/**
* @return {string}
*/
RawFormData.prototype.makeBoundary = function () {
    return 'MyBoundary' + window.btoa(Math.random().toString()).substr(0, 12);
};

/**
* @param {string} name
* @param {string|number|File|Blob|boolean|null|undefined} val
* @param {string=} filename
*/
RawFormData.prototype.append = function (name, val, filename) {
    var prom = null;

    if(val instanceof File || val instanceof Blob){
        prom = this.readAsBinaryString(val).then(function(base64){
            var contentType = val.type || 'application/octet-stream';
            var result = '--' + this._boundry + '\r\n' +
                'Content-Disposition: form-data; ' +
                'name="' + name + '"; filename="' + this.encode_utf8(filename || "blob") + '"\r\n' +
                'Content-Type: ' + contentType + '\r\n\r\n' +
                base64 + '\r\n';
            return result;
        }.bind(this))
    }else{
        prom = new Promise(function(resolve){
            return '--' + this._boundry + '\r\n' +
                'Content-Disposition: form-data; ' +
                'name="' + this.encode_utf8(name) + '"\r\n\r\n' +
                this.encode_utf8(val) + '\r\n'
        }.bind(this));
    }

    this._promises.push(prom);

    return prom;
};
/**
* @return {File|Blob} blob
* @return {Promise<string>}
*/
RawFormData.prototype.readAsBinaryString = function (blob) {
        var reader = new FileReader();
        return new Promise(function(resolve,reject){
            var binStringCallback = function (e) {
                resolve(e.target.result);
            };

            var arrBufferCallback = function (e) {
                var binary = "";
                var bytes = new Uint8Array(e.target.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }
                resolve(binary);
            };

            reader.onerror = reader.onabort = function () {
                resolve(null);
            };

            if (typeof reader.readAsBinaryString != "undefined") {
                reader.onload = binStringCallback;
                reader.readAsBinaryString(blob);
            } else {
                reader.onload = arrBufferCallback;
                reader.readAsArrayBuffer(blob);
            }
        });
};

RawFormData.prototype.encode_utf8 = function( s ){
   return unescape( encodeURIComponent( s ) );
}

RawFormData.prototype.getOutputDeferred = function () {
    return Promise.all(this._promises).then(function (rows) {
        var output = '--' + this._boundry + '\r\n';
        rows.forEach(function(row) {
            output += row;
        });
        output += '--' + this._boundry + '\r\n';
        return output;
    }.bind(this));
};