Second understand javascript drag upload file

Code

Paste the code directly and copy it to the local. html file to achieve the above demonstration effect:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>drag file</title>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
		}
		.container {
			width: 60%;
			max-width: 600px;
			height: 320px;
			padding: 15px;
			margin: 20px auto 0;
			border-radius: 10px;
			background-color: #fce4ec;
		}
		.dashboard {
			width: 100%;
			height: 100%;
			box-sizing: border-box;
			padding: 12px;
			border: 3px dashed #F8BBD0;
			border-radius: 5px;
			font-size: 20px;
			color: #2c1612;
			cursor: text;
			white-space: pre-wrap; 
			/*word-break: break-all;*/
			word-wrap: break-word;
			overflow-y: auto;
		}
	</style>
</head>
<body>
	<div class="container">
		<div id="dashboard" class="dashboard"></div>
	</div>
	<script type="text/javascript">
		var dashboard = document.getElementById("dashboard")
		dashboard.addEventListener("dragover", function (e) {
			e.preventDefault()
			e.stopPropagation()
		})
		dashboard.addEventListener("dragenter", function (e) {
			e.preventDefault()
			e.stopPropagation()
		})
		dashboard.addEventListener("drop", function (e) {
			// Browser default events must be disabled
			e.preventDefault()
			e.stopPropagation()
			var files = this.files || e.dataTransfer.files
			var reader = new FileReader()
			reader.readAsText(files[0], 'utf-8')
			reader.onload = function (evt) {
				var text = evt.target.result
				dashboard.innerText = text
			}
		})
	</script>
</body>
</html>

 

Explain

  • You need to add drop event listening to the target area. In the callback, use the parameter e.dataTransfer.files to get the array of files dragged and uploaded.
  • You need to block browser default behavior in dragover and dragener event listening.
  • The code uses utf-8 to parse the file content. If the file or web page code is not utf-8, there will be garbled code.

Tags: Javascript

Posted on Sun, 05 Apr 2020 15:23:46 -0700 by bivaughn