讓input支持 ctrl v上傳粘貼圖片? 讓input支持QQ截圖或剪切板中的圖像數據(Java實現保存)

原理:監聽粘貼 → 獲取粘貼內容 → 將內容上傳 → 抓取後返回替換至inputphp

咱們在生產中用到的界面: 測試地址 http://sms.reyo.cn 用戶名:aa 密碼:123456ajax

 

 

 

如下是PHP實現:app

<?php
header("Access-Control-Allow-Origin:*");
$url  = 'http://'.$_SERVER['HTTP_HOST'];
$file = (isset($_POST["file"])) ? $_POST["file"] : '';
if($file)
{
    $data = base64_decode(str_replace('data:image/png;base64,', '', $file));  //截圖獲得的只能是png格式圖片,因此只要處理png就好了
    $name = md5(time()) . '.png';  // 這裏把文件名作了md5處理
    file_put_contents($name, $data);
    echo "$url/$name";
    die;
}
?>
 
 
<div id="box" style="width:400px;height:400px;border:1px solid;" contenteditable>
</div>
<input type="hidden" name="img" value="" id="img_puth"/>
 
<script>
    //查找box元素,檢測當粘貼時候,
    document.querySelector('#box').addEventListener('paste', function(e) {
 
        //判斷是不是粘貼圖片
        if (e.clipboardData && e.clipboardData.items[0].type.indexOf('image') > -1) 
        {
            var that     = this,
                reader   = new FileReader();
                file     = e.clipboardData.items[0].getAsFile();
 
            //ajax上傳圖片
            reader.onload = function(e) 
            {
                var xhr = new XMLHttpRequest(),
                    fd  = new FormData();
 
                xhr.open('POST', '', true);
                xhr.onload = function () 
                {
                    var img = new Image();
                    img.src = xhr.responseText;
 
                    // that.innerHTML = '<img src="'+img.src+'" alt=""/>';
                    document.getElementById("img_puth").value = img.src;
                }
 
                // this.result獲得圖片的base64 (能夠用做即時顯示)
                fd.append('file', this.result); 
                that.innerHTML = '<img src="'+this.result+'" alt=""/>';
                xhr.send(fd);
            }
            reader.readAsDataURL(file);
        }
    }, false);
</script>
相關文章
相關標籤/搜索