How to receive php image data over copy-n-paste javascript with XMLHttpRequest

六眼飞鱼酱① 提交于 2019-11-29 04:49:51

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>

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);
}

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!