francois2metz / html5-formdata

Emulate FormData object for some browsers
175 stars 78 forks source link

Cannot be used for AJAX form submission in IE7/8, as relies on forEach #2

Open BMSKiwi opened 11 years ago

BMSKiwi commented 11 years ago

As per title. I fixed this for my own use (although files still don't work obviously) and figured I should post it. Simplified the formatting a little as well.

(function(w){
    if (w.FormData)
        return;
    function FormData(){
        this.fake = true;
        this.boundary = '--------FormData' + Math.random();
        this._fields = [];
    }
    FormData.prototype.append = function(key, value){
        this._fields.push([key, value]);
    }
    FormData.prototype.toString = function(){
        var boundary = this.boundary;
        var body = '';
        for(var i = 0; i < this._fields.length; i++){
            if (this._fields[i][1].name) {
                var file = this._fields[i][1];
                body += 'Content-Disposition: form-data; name="'+ this._fields[i][0] + '"; filename="' + file.name + '"\r\n';
                body += 'Content-Type: ' + file.type + '\r\n\r\n';
                body += file.getAsBinary() + '\r\n';
            }
            else{
                  body += '--' + boundary + '\r\n';
                  body += 'Content-Disposition: form-data; name="' + this._fields[i][0] + '";\r\n\r\n';
                  body += this._fields[i][1] + '\r\n';
            }
        };
        body += '--' + boundary + '--';
        return body;
    }
    w.FormData = FormData;
})(window);
anhnt commented 10 years ago

It should work on IE 8 since IE 8/9 does not support Array.forEach method. thanks @BMSKiwi

PunkChameleon commented 9 years ago

Does this plugin work for files in IE 9 below? Very confusing to read the issues.

francois2metz commented 9 years ago

IE < 10 does't support the Fileapi. Would be difficult. http://caniuse.com/#search=fileapi

PunkChameleon commented 9 years ago

Doesn't the readme show a file being uploaded with this command? data.append('file', document.getElementById('file').files[0]);

and FormData is supported in 10 and up, right? I was under the impression that this was a shim for FormData for legacy browsers? (Thank you for your quick response, btw)

PunkChameleon commented 9 years ago

I'm a bit of a situation where I need to implement a shim for FormData in a legacy project for file uploads (already built for every other browser). Can this help?