如何使用XMLHttpRequest通过copy-n-paste javascript接收php图像数据

poi*_*oae 5 javascript php xmlhttprequest image-uploading onpaste

我尝试制作类似于GMail使用的图像上传功能.您从桌面复制(CTRL-C)图像并将其粘贴(CTRL-V)到网站上.然后通过XMLHttpRequest将图像上传到处理传入文件的php脚本,其中"处理"意味着重命名并存储在服务器上.

我已经可以获取图像(和-data),但我无法成功提交和接收XMLHttpRequest.我的Javascript代码看起来像这样:

  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);
    }
Run Code Online (Sandbox Code Playgroud)

处理php(php/image-upload.php)看起来像这样:

$base64string = $_POST['file'];
file_put_contents('img.png', base64_decode($base64string));
Run Code Online (Sandbox Code Playgroud)

我认为$_POST['file']留空,但我不确定.更重要的是,我还遇到"blob size"(用console.log()显示)比实际图像大小大.但也许这无论是编码还是由编码造成的.

开发者控制台显示此信息.

{"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}
Run Code Online (Sandbox Code Playgroud)

如果我通过右键单击实际图像文件来查看文件信息,则会显示5,320 bytes (8 KB on disk)大小.

我不一定需要使用a XMLHttpRequest,这是我首先想到的.如果有更好的方法使用javascript实现实时图像上传到服务器,请告诉我们.

Esa*_*ija 7

您从桌面复制(CTRL-C)图像并将其粘贴(CTRL-V)到网站上.

不,那是不可能的.您可以粘贴的是例如来自网络的屏幕截图和图像,这就是gmail所做的.

您最大的错误是在已有文件时使用FileReader,当$_FILES正确的HTTP上载不是ad hoc base64 POST参数时,数组会被填充.要进行正确的HTTP上传,您只需要.append()一个文件或blob对象(Files是Blobs).

这是一个独立的PHP文件,应该只能工作,托管文件,打开它是一个页面,截取屏幕截图,然后在页面上粘贴它,几秒钟后图像应该出现在页面上.

<?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>
Run Code Online (Sandbox Code Playgroud)