首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實現截圖粘貼上傳:前端 clipboardData + 後端 Base64 解碼

     編輯:PHP 相關知識

原理:監聽 paste 事件 → FileReader 讀取圖片 → Base64 → AJAX POST → PHP 解碼保存

前端 HTML + JavaScript

<div id="box" contenteditable></div>
<input type="hidden" name="img" value="" id="img_puth"/>
<script>
document.querySelector('#box').addEventListener('paste', function(e) {
    if (e.clipboardData && e.clipboardData.items[0].type.indexOf('image') > -1) {
        var that = this, reader = new FileReader();
        var file = e.clipboardData.items[0].getAsFile();
        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;
                document.getElementById("img_puth").value = img.src;
                that.innerHTML = '<img src="' + img.src + '" alt=""/>';
            };
            fd.append('file', this.result); // Base64 字符串
            xhr.send(fd);
        };
        reader.readAsDataURL(file);
    }
}, false);
</script>

後端 PHP 接收並保存

<?php
header("Access-Control-Allow-Origin:*");
$url = 'https://' . $_SERVER['HTTP_HOST'];
$file = isset($_POST["file"]) ? $_POST["file"] : '';
if ($file) {
    // 移除 data:image/png;base64, 前綴
    $data = base64_decode(str_replace('data:image/png;base64,', '', $file));
    $name = md5(time()) . '.png';
    file_put_contents($name, $data);
    echo $url . '/' . $name;
    exit;
}
?>

注意:僅處理 PNG 格式(截圖默認 PNG),生產環境需增加文件類型驗證、大小限制、存儲路徑管理等安全措施。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved