Here’s the code I use to upload a binary file to a server:
var params = { baseURL:"http://example.com:8080", MIMEType:"application/pdf" } ;
var restClient = new RestClient( params );
var xhr = restClient.uploadFile( "/uploadPDF2", Watch.GetJobFileName() )
if(xhr.status>=200 && xhr.status<300) {
Watch.log("File uploaded successfully",2);
} else {
Watch.log("Error " + xhr.status + " while uploading file",1);
}
function RestClient(conf){
var xhr = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
xhr.setTimeouts(30000,30000,0,0);
this.baseURL = conf.baseURL;
this.token = conf.token;
this.MIMEType = conf.MIMEType || "application/octet-stream";
this.uploadFile = function(endPoint, fName){
fName = fName.replace(/\\/g,"/");
var bStream = openXHRStream(fName);
xhr.open("POST", this.baseURL + endPoint, false);
if(this.token) xhr.setRequestHeader("auth_token", this.token);
xhr.setRequestHeader("Content-Type", this.MIMEType);
xhr.send(bStream);
bStream = null;
return xhr;
}
openXHRStream = function(fName){
// Open a stream with XMLHTTP
var xhr2 = new ActiveXObject("Msxml2.XMLHTTP.6.0");
xhr2.open("GET", "file:///" + fName, false);
xhr2.send();
return xhr2.responseStream;
}
}
The code uses an HTTPRequest.responseStream
to upload the file, thereby ensuring that the data is not transformed in any way. This method can be used for any type of file. Ideally, you would always set the mime type to the appropriate value, but even if you don’t, then the data is uploaded as application/octet-stream
which instructs the server on the receiving end to treat the file as binary data, thus preventing any kind of transformation from occurring on the server.