接受從粘貼到瀏覽器視窗中的影像上傳比傳統的檔案上傳表單輸入甚至更新樣式的拖放檔案上傳要容易得多。
我該如何實施?
uj5u.com熱心網友回復:
這是一個接受拖放影像上傳的示例 PHP/JavaScript 頁面。但它并不依賴于 PHP——你可以很容易地調整它以使用另一種基于服務器的語言。這段代碼基于我在 jsFiddle 上由 Nick 找到的一個片段。
這是一個完整的頁面 - 所以您應該能夠復制下面的代碼并將其按原樣放在您的網路服務器上的檔案中(如果您沒有運行 PHP,那么您需要在top 或將表單指向您自己的表單處理程式腳本)。
<?php
if (!empty($_POST)) {
// Handle the POSTed data here - the image is actually base64 encoded data in
// the $_POST['myTextarea'] variable which you can run through the base64_decode()
// function and then write to a file
$pos = strpos($_POST['myTextarea'], 'base64,');
$encoded = substr($_POST['myTextarea'], $pos 7);
$raw = base64_decode($encoded);
// Show the base64 encoded $data - use the $raw variable when writing to a file
var_dump($_POST);
exit;
}
?>
<!DOCTYPE html >
<html>
<body>
<h1>File upload using paste</h1>
<p>
You can paste an image, which is on your clipboard, into this window and it will appear below.
If you use Windows you can press <b>PrtScr</b> to get a screenshot on your clipboard. Then
press <b>CTRL V</b> to paste it into this document.
</p>
<!-- PUT THE ADDRESS OF YOUR FORM HANDLER SCRIPT IN THE ACTION ATTRIBUTE -->
<form action="" method="post">
<div id="form-elements-container">
<input type="text" value="An example text input..." name="myTextInput"><br />
<input type="submit" value="Submit form"><br />
</div>
</form>
<!-- THIS IS WHERE THE IMAGE THUMBNAILS WILL APPEAR -->
<div id="images-container"></div>
<script>
counter = 0;
document.body.onpaste = function (e)
{
// use event.originalEvent.clipboard for newer chrome versions
var items = (e.clipboardData || e.originalEvent.clipboardData).items;
// Find pasted image among pasted items
var blob = null;
for (var i=0; i<items.length; i ) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
// Load image if there is a pasted image
if (blob !== null) {
var reader = new FileReader();
reader.onload = function(e)
{
// Create a new image object from the pasted data
var img = new Image();
img.src = e.target.result;
img.width = 128;
img.height = 128;
img.style.margin = '5px';
// Append the file to the document
document.getElementById('images-container').appendChild(img);
// Add a new textarea to the form
var textarea = document.createElement('textarea');
textarea.name = 'myTextarea_' counter ;
textarea.value = img.src;
textarea.style.width = '200px';
textarea.style.height = '200px';
document.getElementById('form-elements-container').appendChild(textarea);
};
reader.readAsDataURL(blob);
}
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510402.html
標籤:形式图片剪贴板图像数据
