使用js來實現類似word剪切板的效果,即複製黏貼圖片,而js也正好提供了這種可能,那就是textarea的事件驅動,監視textarea的黏貼事件,一旦出現黏貼就將獲得的圖片上傳到服務器,在從服務器中拿出顯示到頁面上,獲得圖片數據的方法也可以用js中提供的clipboard的方式獲取,下面是個例子,
通過clipboard獲取後打上斷點,查看剪貼板上的數據可以發現在items下的數據爲kind爲file,type爲“image/png”
那麼方法就確定了,當KInd爲file且type中包含image字樣就將該數據上傳,上傳方法採用ajax即可,寫在事件中,通過getasfile函數獲得圖片數據,並寫入到表單中,通過ajax上傳即可,具體過程如下:
document.getElementsByTagName("textarea")[0].addEventListener('paste', function(e) {
var clipboard = e.clipboardData;
for(var i=0,len=clipboard.items.length; i<len; i++) {
if(clipboard.items[i].kind == 'file' || clipboard.items[i].type.indexOf('image') > -1) {
var imageFile = clipboard.items[i].getAsFile();
var form = new FormData;
form.append('avatar', imageFile);
//var callback = G.uploadpicCallback || function(type, data){};
$.ajax({
url: "uploadimage.php",
type: "POST",
data: form,
processData: false,
contentType: false,
beforeSend: function() {
$('#uploadmessage').html('正在上傳圖片...');
},
error: function() {
$('#uploadmessage').html('上傳失敗請重新上傳!');
alert('圖片上傳失敗');
},
success: function(url) {
$('#uploadmessage').html('圖片上傳成功');
setTimeout('$(\'#uploadmessage\').html(\'\')', 1000);
var img=new Image();
img.src=url;
document.getElementById('uploadmessage').appendChild(img);
//textarea.val(textarea.val() + '[![]('+url+')]('+url+')')*/
}
})
e.preventDefault();
}
uploadimage.php,最簡單的上傳函數,如果要實現更復雜的文字圖片一起上傳的話,js文件和php上傳操作都需要對應的修改
if(!is_dir("./images"))
{
mkdir("./images");
}
if($_FILES['avatar']['tmp_name']){
$img=$_FILES['avatar']['tmp_name'];
preg_match("/\w*\./",$img,$img_name);
$path="images/".$img_name[0]."png";
if(move_uploaded_file($img,$path)){
$result=true;
echo $path;
}else{
$result=false;
// echo $path;
}
}