let reader = new FileReader() ;
文件讀取主要事件javascript
文件讀取的方式css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>文件拖拽</title>
<style> #div1 { width: 500px; height: 500px; background: #cccccc; border: 1px solid #000000; text-align: center; line-height: 500px; } </style>
<script> window.onload = function () { var div1 = document.getElementById("div1"); //拖拽進入 div1.addEventListener("dragenter", function () { div1.innerHTML = "請鬆手" ; }, false); //拖拽離開 div1.addEventListener("dragleave", function () { div1.innerHTML = "拖到這裏上傳" ; }, false); //懸停 div1.addEventListener("dragover", function (ev) { ev.preventDefault();//取消事件的默認動做,防止瀏覽器打開文件 }, false); //鬆手 div1.addEventListener("drop", function (ev) { ev.preventDefault();//取消事件的默認動做。 let fileReader = new FileReader() ; let file = ev.dataTransfer.files[0] ; fileReader.onload = function(){ alert("成功"+this.result); } fileReader.onerror = function(){ alert("讀取失敗"); } fileReader.readAsText(file) ; }, false); } </script>
</head>
<body>
<div id="div1">拖到這裏上傳</div>
</body>
</html>
複製代碼