I'm writing a Chrome extension, and need to build a custom Form data to upload a Zip file (I can't use a real HTML form) to a server (not mine). I found a way to do it here - https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_forms_through_JavaScript (last section - Dealing with binary data).
It works fine with clear text files, but I want to send Zip which is binary.
It seems that JavaScript can't handle concatenation of binary and non binary, and adds some 0Xc2 chars to my file )-:
I also found a solution at http://footle.org/2007/07/31/binary-multipart-posts-in-javascript/,
but it uses Components.classes["@mozilla.org/io/string-input-stream;1"], which is not usable in Chrome extension.
How can I concatenate a binary zip file with a string and upload it to a server?
function sendData(zipBinary) {
var XHR = new XMLHttpRequest();
var boundary = "----WebKitFormBoundary3n9vu9ZOkCPW4HAw";
var prefix = "";
var postfix = "";
prefix += "--" + boundary + "\r\n";
prefix += 'content-disposition: form-data; '
+ 'name="' + 'UploadedFile' + '"; '
+ 'filename="' + 'hello.zip' + '"\r\n';
prefix += 'Content-Type: ' + 'application/x-zip-compressed' + '\r\n';
prefix += '\r\n';
postfix += '\r\n';
// Once we are done, we "close" the body's request
postfix += "--" + boundary + "--";
postfix += '\r\n';
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
});
XHR.addEventListener('error', function(event) {
alert('Oups! Something goes wrong.');
});
XHR.open('POST', 'https://example.com');
XHR.setRequestHeader('Content-Type','multipart/form-data; boundary=' + boundary);
XHR.send(prefix + zipBinary + postfix); // <----
}