溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

利用php怎么實現(xiàn)一個截圖上傳功能

發(fā)布時間:2020-12-21 15:43:05 來源:億速云 閱讀:138 作者:Leah 欄目:開發(fā)技術(shù)

利用php怎么實現(xiàn)一個截圖上傳功能?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

原理很簡單其實就是監(jiān)控粘貼事件,然后檢測是否粘貼的東西里面有圖片,有的話直接觸發(fā)ajax上傳

代碼可以直接運行,有興趣你們可以試試

<?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"contenteditable>
</div>
<input type="hidden"name="img"value=""id="img_puth"/>

<script>
//查找box元素,檢測當(dāng)粘貼時候,
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>

關(guān)于利用php怎么實現(xiàn)一個截圖上傳功能問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI