-
Notifications
You must be signed in to change notification settings - Fork 14
/
016.拖动文件上传.html
89 lines (79 loc) · 2.61 KB
/
016.拖动文件上传.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./assets/global.css">
<style>
#drag {
width: 500px;
height: 300px;
border-radius: 10px;
background-color: #f8f8f8;
border: 2px dashed #ddd;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
color: #777;
user-select: none;
}
#image {
width: 500px;
height: 300px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="drag">拖动至此上传文件</div>
<img id="image" />
<p id="fileName"></p>
<script>
let dragDivDom = document.getElementById('drag');
let imageImgDom = document.getElementById('image')
let fileNamePDom = document.getElementById('fileName');
imageImgDom.hidden = true;
fileNamePDom.hidden = true;
dragDivDom.addEventListener('drop', (ev) => {
// 阻止进行拖拽时浏览器的默认行为
ev.preventDefault();
// 取得文件
let file = ev.dataTransfer.files[0]
// 是否是图像
let isImage = file.type.includes('image')
// 文件读取器
let reader = new FileReader();
// 如果是图像
if (isImage) {
reader.readAsDataURL(file);
reader.addEventListener("load", (res) => {
imageImgDom.setAttribute('src', res.target.result)
})
}
// 是否隐藏
imageImgDom.hidden = !isImage;
fileNamePDom.hidden = false;
fileNamePDom.textContent = `文件名:${file.name}`
// 上传文件
let data = new FormData();
data.append('file', file);
let r = new XMLHttpRequest();
r.open("post", "文件服务器地址");
r.onloadend = () => {
console.log(JSON.parse(r.responseText))
}
r.send(data);
})
dragDivDom.addEventListener('dragover', (ev) => {
// 阻止进行拖拽时浏览器的默认行为
ev.preventDefault();
})
dragDivDom.addEventListener('dragend', (ev) => {
// 阻止进行拖拽时浏览器的默认行为
ev.preventDefault();
})
</script>
</body>
</html>