上代碼,包去網上找,看不懂問度娘。
<html> <head> <script src="jquery.min.js"></script> </head> <body> <div class="preview" data-id=1 style="width:100px;height:100px;background:#ff0000">容器 1 </div> <div class="preview" data-id=2 style="width:100px;height:100px;background: #222222">容器 2 </div> <div class="preview" data-id=3 style="width:100px;height:100px;background: #ff12ff">容器 3 </div> <div class="preview" data-id=4 style="width:100px;height:100px;background:#120013">容器 4</div> <div class="preview" data-id=5 style="width:100px;height:100px;background:#00ff00">容器 5 </div> <p id="log"></p> <script> document.addEventListener('paste', function (event) { console.log(event); var items = (event.clipboardData || window.clipboardData).items; var file = null; if (items && items.length) { // 搜索剪切板items for (var i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') !== -1) { file = items[i].getAsFile(); break; } } } else { log.innerHTML = '<span style="color:red;">當前瀏覽器不支持</span>'; return; } if (!file) { log.innerHTML = '<span style="color:red;">粘貼內容非圖片</span>'; return; } console.log(file); // 此時file就是我們的剪切板中的圖片對象 // 如果需要預覽,可以執行下面代碼 var reader = new FileReader() reader.onload = function(event) { var targetHtml = '<img width=100px height=100px src="' + event.target.result + '" class="upload-image">'; $(".active").html(targetHtml); } reader.readAsDataURL(file); // 如果不需要預覽,上面這段可以忽略 // 這裏是上傳 var xhr = new XMLHttpRequest(); // 上傳進度 if (xhr.upload) { xhr.upload.addEventListener('progress', function (event) { log.innerHTML = '正在上傳,進度:' + Math.round(100 * event.loaded / event.total) / 100 + '%'; }, false); } // 上傳結束 xhr.onload = function () { var responseText = xhr.responseText; log.innerHTML = '上傳成功,地址是:' + responseText; }; xhr.onerror = function () { log.innerHTML = '<span style="color:red;">網絡異常,上傳失敗</span>'; }; xhr.onreadystatechange = function () { if(xhr.readyState == 4 && xhr.status == 200){ var b = xhr.responseText; b=JSON.parse( b ); console.log(b); } }; xhr.open('POST', '/vehicles/uploadimages?uid='+<?php echo $arrVehicles['uid'];?>, true); // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader('File', encodeURIComponent(file.name)); data = new FormData(); data.append("file", file); xhr.send(data); // var data; // if (type === "formdata") { // data = new FormData(); // data.append("key", "value"); // } else if (type === "json") { // xhr.setRequestHeader("Content-Type", "application/json"); // data = JSON.stringify({"key": "value"}); // } else if (type === "text") { // data = "key=value"; // } else if (type === "www") { // // 傳統post 表單的格式 // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // data = "key=value"; // } }); $(document).ready(function(){ $(".preview").click(function () { $(".preview").removeClass('active'); $(this).addClass('active'); }) }); </script> </body> </html>