傳送門:
-
1. JavaScript 教程 / 瀏覽器模型 / ArrayBuffer 物件,Blob 物件
-
2. HTML5 - 通過拖拽讀取圖片檔案(將電腦中圖片拖入瀏覽器並顯示)
-
3. js實現file上傳圖片在div中顯示與點選div觸發file表單
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.dropArea {
margin: 0 auto;
width: 600px;
height: 300px;
text-align: center;
line-height: 300px;
font-size: 2em;
font-weight: bold;
color: gray;
border: 5px dashed gray;
background-color: #e6e6e6;
overflow: hidden;
cursor: pointer;
}
</style>
</head>
<body>
<div class="dropArea">
<span>拖放區..</span>
<input type="file" accept="image/*" multiple style="display: none;" "/>
</div>
<div class="thumbnail"></div>
<script type="text/javascript">
const dropArea = document.querySelector('.dropArea');
const thumbnail = document.querySelector('.thumbnail');
const file = document.querySelector('input[type="file"]');
function ignoreDrag(e) {
e.preventDefault();
}
function fileinfo() {
file.onchange = function() {
dropArea.innerHTML = null;
for (var i = 0; i < this.files.length; i++) {
var img = document.createElement('img');
img.src = window.URL.createObjectURL(this.files[i]);
img.width = 600;
dropArea.appendChild(img);
img.onload = function() {
window.URL.revokeObjectURL(this.src);
}
}
}
}
dropArea.addEventListener('dragenter', ignoreDrag, false);
dropArea.addEventListener('dragover', ignoreDrag, false);
dropArea.addEventListener('drop', function(e) {
ignoreDrag(e);
var files = e.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
var type = files[i].type;
if (type.substring(0, 6) !== 'image/') continue;
var img = document.createElement('img');
img.src = URL.createObjectURL(files[i]);
img.onload = function() {
this.width = 100;
thumbnail.appendChild(this);
URL.revokeObjectURL(this.src);
}
}
}, false);
dropArea.addEventListener('click', function(e) {
var evt = new MouseEvent('click', {
bubbles: false,
cancelable: true,
view: window
});
file.dispatchEvent(evt, fileinfo());
}, false);
</script>
</body>
</html>