Apologies for any language barriers. I am trying to upload my (.exe) file selected using an input file:
<input type="file" id="myfile">
Here is how it should be read in Javascript:
var myfile='';
var input = document.getElementById('myfile');
input.onchange = function(evt){
var tgt = evt.target || window.event.srcElement, files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function(){
myfile = fr.result;
}
fr.readAsDataURL(files[0]);
}
}
Now, the variable "myfile" looks like this:
"data:application/msdownload;base64,0J/RgNC40LLQtdGCINC80LjRgCE= .... etc."
The base64 part contains the source file that was selected. However, when attempting to upload the file, its encoding and size change, resulting in corruption. What could I be doing wrong?
Here is the upload code being used:
var fd = new FormData();
var b = new Blob([atob(decodeURIComponent((myfile).split(',')[1]))],{type: 'application/msdownload'});
fd.append('file', b, "myfile.exe");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myserver/");
xhr.send(fd);
The file uploads successfully. However, upon downloading it again, the file ends up corrupted with changed encoding and size.
I have tried setting different headers like so:
xhr.setRequestHeader("Content-Type", "charset=windows-1251");
.............
xhr.setRequestHeader("Content-Type", "charset=utf-8");
But unfortunately, nothing seems to make a difference...
I am able to upload the file without AJAX, but I do need to retain the file locally and then upload it from a variable after manipulation.
In summary:
I have a Base64 encoded string like this:
0J/RgNC40LLQtdGCINC80LjRgCE=
I know this string represents the file "SecretFile.exe". I want to decode and upload this file using JavaScript. However, using standard window.atob to decode the string does not match the original file source. How can I properly decode this Base64 encoded file using FileReader?
Thank you.