Page 1 of 1

file uploading with html5 and ajax issue

Posted: Wed Apr 06, 2011 12:43 pm
by matpiet
ok I am having issues with my file size changing after I upload.

var reader = new FileReader();
reader.readAsBinaryString(file);
I send the file object like this...

Code: Select all

var http = new XMLHttpRequest();
  var url = "upload.php";
	
  http.open("POST", url, true);

  //Send the proper header information along with the request
  //http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  //http.setRequestHeader("Content-length", 0);
  //http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
			 	div.innerHTML = http.responseText;
	}
 }
 http.send(file);
when I output the size of the file object in javascript
file.length
it returns with the value 69,874 bytes which is the exact file size.

after the post on the php end of thing I use this simple code to read the file

Code: Select all

<?php
$postdata = file_get_contents("php://input");
echo "File size on the server is: ".strlen(stripslashes($postdata))." bytes. <br />";
echo $postdata;
$fp = fopen("fighter.txt", "wb");
fwrite($fp, $postdata);
fclose($fp);
?>
it returns the size 88648 bytes

where is the extra data coming from do you guys have any idea?

Re: file uploading with html5 and ajax issue

Posted: Thu Apr 07, 2011 10:32 am
by matpiet
ok I figured it out and it had nothing to do with php. When I was transmitting the file object using the XMLHttpRequest objects send() function it expects text so it manipulates the data somehow causing the file size to grow. What worked for me was using the sendAsBinary() function which is built into Firefox but has to be added to chrome using this work around...

Code: Select all


XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
        var bb = new BlobBuilder();
        var data = new ArrayBuffer(1);
        var ui8a = new Uint8Array(data, 0);
        for (var i in datastr) {
                if (datastr.hasOwnProperty(i)) {
                        var chr = datastr[i];
                        var charcode = chr.charCodeAt(0)
                        var lowbyte = (charcode & 0xff)
                        ui8a[0] = lowbyte;
                        bb.append(data);
                }
        }
        var blob = bb.getBlob();
        this.send(blob);
}