I'm trying to upload a static file from within my JS code. I have a .tgz file that I want to send as POST parameter. I've dumped my file to a hex string fileDatalike: var file = "\xff\x01\x08 .....
I want to send as the body content of a multi form post data. It seems like when I try to just .send(file) the hex values become mangled and the file is corrupted.
JS looks something like this:
var url = "/index/upload/"
var fileData = '\xF1\x08\x00\x00........\x00\x00';
//whole file binary content in hex)
boundary = "----------3333338220322",
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary);
var body = "--" + boundary + "\r\n";
body += 'Content-Disposition: form-data; name="newFile"; filename="filename.tgz"\r\n';
body += "Content-Type: application/x-gzip\r\n\r\n";
body += fileData + "\r\n";
body += "--" + boundary + "--";
xhr.send(body);
Not sure what goes wrong. The request seems to look exactly like if I manually upload the file, but the binary data seems different when observing through a proxy. Is there a better way to send files if i need to have its whole content in the JS code itself?
Figured out a wait to make it work. Using base64 to encode the file instead of hex.
var b64data = 'H4sIAHegu.....';
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const contentType = 'application/x-gzip';
const blob = b64toBlob(b64data, contentType);
Then used this blob as the file content.
Solution found from here:
Convert base64 png data to javascript file objects
offsec/awae ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With