JPEG data retrieved from FileReader does not match data in file

I am trying to select a local JPEG file in a web browser using HTML5 FileReader so that I can send it to the server without reloading the page. All the mechanics work, and I think that I transfer and save the exact data that JavaScript gave me, but the result is an invalid JPEG file on the server. Here is the base code that demonstrates the problem:

<form name="add_photos"><input type="file" name="photo" id="photo" /><br /><input type="button" value="Upload" onclick="upload_photo()​;​" /></form>

<script type="text/javascript">
    function upload_photo() {
        file = document.add_photos.photo.files[0];
        if (file) {
            fileReader = new FileReader();
            fileReader.onload = upload_photo_ready;
            fileReader.readAsBinaryString(file);
        }
    }

    function upload_photo_ready(event) {
        data = event.target.result;
        // alert(data);

        URL = "submit.php";
        ajax = new XMLHttpRequest();
        ajax.open("POST", URL, 1);
        ajax.setRequestHeader("Ajax-Request", "1");
        ajax.send(data);
    }
</script>

Then my PHP script does this:

$data = file_get_contents("php://input");
$filename = "test.jpg";
file_put_contents($filename, $data);
$result = imagecreatefromjpeg($filename);

A PHP error occurs on this last line: "test.jpg is not a valid JPEG file." If I download the data back to my Mac and try to open it in Preview, Preview reports that the file "may be corrupted or use a file format that Preview does not recognize."

, , , . :

ˇÿˇ‡JFIFˇ˛;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

:

ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

, JavaScript , , , , FileReader , , . - ?

Safari 6, Firefox 14.

UPDATE: , FileReader ajax.send(data) ajax.send(), . , , , readAsBinaryString .

+5
1

readAsBinaryString. byte-for-byte , PHP . ; XmlHttpRequest , UTF-8.

, , , UTF-8... 127!

readAsArrayBuffer readAsBinaryString. ( , ).

+4

All Articles