title: Uploading larger image file from javascript XMLHttpRequest blob to php (it saved wrong size)
body: <p>I am trying to upload larger image file 100MB to php server.
  It looks like a whole file uploaded (got status 200), but on server side there is wrong file size, lost few bytes, and it is not displayed as image in web browser.</p>
  <p>How to fix?</p>
  <p>Here is htmlp/javascript :</p>
  <pre><code>var file = document.getElementById(&quot;selectedfile&quot;).files[0];
  var reader = new FileReader();
  //reader.readAsBinaryString(file); 
  reader.readAsDataURL(file);
  
  reader.onloadend  = function(evt){
  
      xhr = new XMLHttpRequest();
  
      xhr.open(&quot;POST&quot;, &quot;uprx.php?filename=&quot;+document.getElementById(&quot;selectedfile&quot;).files[0].name, true);
  
      XMLHttpRequest.prototype.mySendAsBinary = function(text){
          var data = new ArrayBuffer(text.length);
          var ui8a = new Uint8Array(data, 0);
          for (var i=0; i&lt;text.length; i++) {
              ui8a[i] = (text.charCodeAt(i)&amp;0xff);
          }
          if  (typeof window.Blob == &quot;function&quot;) {
               var blob = new Blob([data]);
          }
          else {
              var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
              bb.append(data);
              var blob = bb.getBlob();
          }
  
          this.send(blob);
      }
  
      var eventSource = xhr.upload || xhr;
      eventSource.addEventListener(&quot;progress&quot;, function(e) {
  
          var position = e.position || e.loaded;
          var total = e.totalSize || e.total;
          var percentage = Math.round((position/total)*100);
  
          
      });
  
      xhr.onreadystatechange = function() {
          if (xhr.readyState == 4)    {
              if (xhr.status == 200) {
                  
              }
              else {
                  // process error
              }
          }
      };
  
      xhr.mySendAsBinary(evt.target.result);
  };
  </code></pre>
  <p>Here is php server :</p>
  <p>$inputHandler = fopen(&quot;php://input&quot;, &quot;r&quot;);</p>
  <p>$fileHandler = fopen($_GET[&quot;filename&quot;], &quot;w&quot;);</p>
  <p>while(true) {</p>
  <pre><code>$buffer = fgets($inputHandler, 4096);
  if (strlen($buffer) == 0) {
      fclose($inputHandler);
      fclose($fileHandler);
      return true;
  }
  
  $base64Image = trim($buffer);
  $base64Image = str_replace('data:image/png;base64,', '', $base64Image);
  $base64Image = str_replace('data:image/jpg;base64,', '', $base64Image);
  $base64Image = str_replace('data:image/jpeg;base64,', '', $base64Image);
  $base64Image = str_replace('data:image/gif;base64,', '', $base64Image);
  //$base64Image = str_replace(' ', '+', $base64Image);
  $imageData = base64_decode($base64Image);
  fwrite($fileHandler, $imageData);
  </code></pre>
  <p>}</p>