欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php實(shí)現(xiàn)粘貼截圖并完成上傳功能

 更新時(shí)間:2015年05月17日 16:49:39   投稿:hebedich  
知乎回答問(wèn)題編輯框用 Ctrl+V 粘貼圖片是如何實(shí)現(xiàn)的?剛發(fā)現(xiàn)知乎編輯器有這么強(qiáng)的功能,在研究的過(guò)程中發(fā)現(xiàn)原來(lái)segmentfault也實(shí)現(xiàn)了這么強(qiáng)大的功能,下面結(jié)合2者來(lái)看看我們?nèi)绾螌?shí)現(xiàn)。

今天發(fā)現(xiàn)segmentfault的評(píng)論留言里面可以粘貼上傳圖片,于是研究了下怎么實(shí)現(xiàn)的!
原理很簡(jiǎn)單其實(shí)就是監(jiān)控粘貼事件,然后檢測(cè)是否粘貼的東西里面有圖片,有的話直接觸發(fā)ajax上傳

代碼可以直接運(yùn)行,有興趣你們可以試試

<?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元素,檢測(cè)當(dāng)粘貼時(shí)候,
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 (可以用作即時(shí)顯示)
 fd.append('file', this.result); 
 that.innerHTML = '<img src="'+this.result+'"alt=""/>';
xhr.send(fd);
}
reader.readAsDataURL(file);
}
}, false);
</script>

以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。

相關(guān)文章

最新評(píng)論