Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I try to make an image-upload functionality similar to the one GMail uses. You copy (CTRL-C) an image from your desktop and paste (CTRL-V) it onto the website. The image is then uploaded via a XMLHttpRequest to a php-script that handles the incoming file, whereby "handling" means renaming and storing on the server.

I can already fetch the image (and -data), but I am unable to successfully submit and receive the XMLHttpRequest. My Javascript code looks like that:

  document.onpaste = function(e){
        var items = e.clipboardData.items;
        console.log(JSON.stringify(items));
        if (e.clipboardData.items[1].kind === 'file') {
            // get the blob
            var imageFile = items[1].getAsFile();
            console.log(imageFile);
            var reader = new FileReader();
            reader.onload = function(event) {
                console.log(event.target.result); // data url!
                submitFileForm(event.target.result, 'paste');
            };
        }
    };

 function submitFileForm(file, type) {
        var formData = new FormData();
        formData.append('file', file);
        formData.append('submission-type', type);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'php/image-upload.php');
        xhr.onload = function () {
            if (xhr.status == 200) {
                console.log('all done: ');
            } else {
                console.log('Nope');
            }
        };

        xhr.send(formData);
    }

The handling php (php/image-upload.php) looks like that:

$base64string = $_POST['file'];
file_put_contents('img.png', base64_decode($base64string));

I think the $_POST['file'] stays empty, but I am not sure. What's more, I also encounter the "blob size" (displayed with console.log()) is way larger than the actual image size. But maybe that's no matter or caused by encodings.

The developer console displays this.

{"0":{"type":"text/plain","kind":"string"},"1":{"type":"image/png","kind":"file"},"length":2} image-upload.js:8
Blob {type: "image/png", size: 135619, slice: function}

If I view the file-info by right-clicking the actual image file, it shows 5,320 bytes (8 KB on disk) in size.

I do not necessarily need to use a XMLHttpRequest, it was just what came to my mind first. If there's a better way of achieving realtime image-uploading to a server with javascript, please let us know.

share|improve this question
 
what does the network tab of your developer console shows. is the file being actually submitted over the wire or an empty form is being sent. –  DevZer0 Aug 5 at 10:06
 
@DevZer0 I added it –  poitroae Aug 5 at 10:10
 
your reader.onload = function(event) { console.log(event.target.result); // data url! submitFileForm(event.target.result, 'paste'); }; function is not firing. –  DevZer0 Aug 5 at 10:19

4 Answers

up vote 0 down vote accepted
+150

you copy (CTRL-C) an image from your desktop and paste (CTRL-V) it onto the website.

No, that is impossible. What you can paste is e.g. screenshots and images from the web, that's what gmail does.

Your biggest mistake is using FileReader when you already have a file, the $_FILES array is filled when there is a proper HTTP upload not for ad hoc base64 POST param. To do a proper HTTP upload, you just .append() a file or blob object (Files are Blobs).

This is a stand-alone PHP file that should just work, host the file, open it is a page, take a screenshot, then paste it while on the page and after a few seconds the image should appear on the page.

<?php
if( isset( $_FILES['file'] ) ) {
    $file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
    header("Content-Type: " . $_FILES['file']['type'] );
    die($file_contents);
}
else {
    header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>

<script>
document.onpaste = function (e) {
    var items = e.clipboardData.items;
    var files = [];
    for( var i = 0, len = items.length; i < len; ++i ) {
        var item = items[i];
        if( item.kind === "file" ) {
            submitFileForm(item.getAsFile(), "paste");
        }
    }

};

function submitFileForm(file, type) {
    var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
    var formData = new FormData();
    formData.append('file', file, "image_file");
    formData.append('extension', extension );
    formData.append("mimetype", file.type );
    formData.append('submission-type', type);

    var xhr = new XMLHttpRequest();
    xhr.responseType = "blob";
    xhr.open('POST', '<?php echo basename(__FILE__); ?>');
    xhr.onload = function () {
        if (xhr.status == 200) {
            var img = new Image();
            img.src = (window.URL || window.webkitURL)
                .createObjectURL( xhr.response );
            document.body.appendChild(img);
        }
    };

    xhr.send(formData);
}
</script>
share|improve this answer
 
pathinfo($_FILES['file']['name'])['extension'] was empty :(. If you can tell me how I'll be able to get the image extension it's yours. :) –  poitroae Aug 8 at 10:32
 
@poitroae done :P it will be in $_POST['extension'] –  Esailija Aug 8 at 10:36

i have posted a full working example. The problem before was you needed to construct the blob properly. by injecting the file data inside an array notation

    document.onpaste = function(e){
    var items = e.clipboardData.items;
    console.log(JSON.stringify(items));
    if (e.clipboardData.items[0].kind === 'file') {
            // get the blob
            var imageFile = items[0].getAsFile();
            console.log(imageFile);
            var reader = new FileReader();
            reader.onload = function(event) {
                console.log(event.target.result); // data url!
                submitFileForm(event.target.result, 'paste');
            };
            reader.readAsBinaryString(imageFile);
        }
    };

function submitFileForm(file, type) {
    var formData = new FormData();
    var myBlob = new Blob([file], { "type" : "image/png"} );
    formData.append('file', myBlob, 'file.jpg');
    formData.append('submission-type', type);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/task/file');
    xhr.onload = function () {
        if (xhr.status == 200) {
            console.log('all done: ');
        } else {
            console.log('Nope');
        }
    };

    xhr.send(formData);
}
share|improve this answer
 
Right, I send the data now correctly. Yet, a file of zero bytes is created each time. I also tried using $_FILES but I am not sure that's really right. Any idea on that? –  poitroae Aug 5 at 14:54
 
@poitroae i updated my answer hope you find it ok –  DevZer0 Aug 6 at 2:03
 
Sounds good, but it did not work for me. The file size stays 0 Bytes. Note, that Blob takes an array as its first parameter. Additionally, this way all my $_POST-variables (e.g. 'submission-type') were cleaned out, meaning they are not defined in the php-script. Have you tried it on your own? I would be really thankful if you could help me on that! –  poitroae Aug 6 at 8:54
 
DevZer0 Bounty started! –  poitroae Aug 7 at 10:11
 
@poitroae working code tested and posted :) –  DevZer0 Aug 7 at 10:30
show 1 more comments

Is it possible that the image file size is greater than your 'upload_max_filesize' setting?(usually defaults to 2 meg)

share|improve this answer
 
I doubt it, the image size on disk is 5,320 bytes (8 KB on disk) –  poitroae Aug 5 at 10:13

I guess the file is in the $_FILE array not in the $_POST since it is a file. If not, you may convert the image to a string an send the imagestring as GET request.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.