if (!XMLHttpRequest.prototype.sendAsBinary) {
XMLHttpRequest.prototype.sendAsBinary = function(sData) {
var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
for (var nIdx = 0; nIdx < nBytes; nIdx++) {
ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
}
/* send as ArrayBufferView...: */
this.send(ui8Data);
/* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
};
}
var input = document.querySelector('input[type="file"]');
input.addEventListener('change', function(){
var file = this.files[0];
if(!file) return false;
var xhr = new XMLHttpRequest;
xhr.open('POST', 'handler.php', true);
xhr.onreadystatechenge = function()
{
if(xhr.readyState === 4 && xhr.status === 200)
{
console.log("SEND FILES");
}
};
var segment = [];
segment.push("Content-Disposition: form-data; name=\"" + file.name + "\"; filename=\""+ file.name + "\"\r\nContent-Type: " + file.type + "\r\n\r\n");
var boundary = "---------------------------" + Date.now().toString(16);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary("--" + boundary + "\r\n" + segment.join("--" + boundary + "\r\n") + "--" + boundary + "--\r\n");
}, false);
<form id="xmlUploaderForm" enctype="multipart/form-data">
<label for="file">Upload file</label>
<input class="upfile" type="file" name="file">
<input id="uploadButton" type="button" value="Upload" class="button-primary">
<span style="padding-left: 20px; display: inline-block;" class="button-spinner"></span>
</form>
$('#uploadButton').click(function(){
var formData = new FormData($('#xmlUploaderForm')[0]);
$.ajax({
url: url,
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function(){},
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});