0

i am trying to use XMLHttpRequest to upload file(image) to my server side, well, i check the file size before sending and check the content-length on my request header, they are not the same, here is the code :

var file = 'someFile'; 
var readers = new FileReader();
readers.readAsBinaryString(file);
readers.onload = (function(theFile) {
  return function(e) {                     
       var myData =  e.target.result;
       console.log(myData.length); // this output is 5548
       var xhr = new XMLHttpRequest();
       xhr.open("POST", url, true);
       xhr.setRequestHeader('Content-Type', 'application/octet-stream;');
       // send the collected data as JSON
       xhr.send(myData );
       xhr.onloadend = function () {
          // done               
       };
  })(file);

when i am looking at the content-lenght on my header request i found the length is bigger than the actaul size , some number like ~7500,

how i can make sure the request file data is the same as the actual size of the file?

1 Answers1

1

When you are sending file content it is usually send as base64-encoded string. This increase size of the request in about 30%. Therefore

console.log(myData.length); // this output is 5548

Is not the size of the file it its length. You could use File.name

Dawid C
  • 413
  • 3
  • 10
  • ,,,, thx for the replay ,,, how can i convert the data from base64_encoded to any other type so the size is the same as the actual size ? – Khalid Manasra Feb 05 '15 at 10:06
  • You cannot. Typical file contains characters that are not allowed in JSON. that's why it is converted to base64 string. – Dawid C Feb 05 '15 at 10:08
  • but. wait you are not sending it as a JSON. You use 'application/octet-stream;' content type. Try uploading file this way http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – Dawid C Feb 05 '15 at 10:15