var targetLocation= "/ENDPOINT";
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
function toBytes(datastr) {
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
return ui8a.buffer;
}
if (typeof XMLHttpRequest.prototype.sendAsBinary == 'undefined' && Uint8Array) {
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
this.send(toBytes(datastr));
}
}
function fileUpload(fileData, fileName) {
var fileSize = fileData.length,
boundary = "--------------------------------1337", // MAX 70 chars.
uri = targetLocation,
xhr = new XMLHttpRequest();
var additionalFields = {
}
var fileFieldName = "fieldName";
xhr.open("POST", uri, true);
xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8")
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary="+boundary); // simulate a file MIME POST request.
xhr.setRequestHeader("Content-Length", fileSize);
xhr.withCredentials = "true";
xhr.onreadystatechange = function() {
console.log(xhr.responseText);
}
var body = "";
for (var i in additionalFields) {
if (additionalFields.hasOwnProperty(i)) {
body += addField(i, additionalFields[i], boundary);
}
}
body += addFileField(fileFieldName, fileData, fileName, boundary);
body += "--" + boundary + "--";
xhr.sendAsBinary(body);
return true;
}
function addField(name, value, boundary) {
var c = "--" + boundary + "\r\n"
c += "Content-Disposition: form-data; name='" + name + "'\r\n\r\n";
c += value + "\r\n";
return c;
}
function addFileField(name, value, filename, boundary) {
var c = "--" + boundary + "\r\n"
c += "Content-Disposition: form-data; name='" + name + "'; filename='" + filename + "'\r\n";
c += "Content-Type: application/x-compressed\r\n\r\n";
c += value + "\r\n";
return c;
}
var start = function() {
var c = "HEX-FILE-DATA"
fileUpload(c, "FILE-NAME");
};
start();