一种通过拖拽图片来实现上传的方法,界面比较简陋,后续可以美化下界面
实现效果
代码实现
- 必要的css
* {
margin: 0;
padding: 0;
}
#box {
width: 200px;
height: 200px;
background-color: red;
margin: 100px auto;
text-align: center;
color: #fff;
line-height: 200px;
}
ul {
list-style: none;
}
li {
max-width: 300px;
height: 240px;
position: relative;
}
img {
width: 100%;
height: 100%;
}
.progress {
width: 300px;
height: 20px;
outline: 1px solid #333;
border-radius: 10px;
background-color: pink;
position: relative;
overflow: hidden;
position: absolute;
left:0;
top:50%;
transform: translateY(-50%);
}
.bar{
width:0;
height: 20px;
border-radius: 10px;
background-color: aqua;
}
- 静态页面
<body>
<div id="box">将文件拖拽到此区域</div>
<ul id="list"></ul>
</body>
- 核心逻辑
window.onload = function () {
const oBox = document.getElementById("box");
const oList = document.getElementById("list");
const oListItem = oList.getElementsByTagName("li");
oBox.ondragenter = function (e) {
e = e || window.event;
e.preventDefault();
this.innerHTML = "可以释放啦~";
};
oBox.ondragover = function (e) {
e = e || window.event;
e.preventDefault();
};
oBox.ondragleave = function (e) {
this.innerHTML = "将文件拖拽到此区域~";
};
oBox.ondrop = function (e) {
e = e || window.event;
e.preventDefault(); // 阻止默认行为,图片会打开
this.innerHTML = "将文件拖拽到此区域~";
const data = e.dataTransfer.files;
console.log("🚀 ~ data:", data);
for (let i = 0; i < data.length; i++) {
const type = data[i].type;
if (type.indexOf("image") == -1) {
// alert("文件格式错误");
// return false;
}
// 读取文件内容
const reader = new FileReader();
reader.readAsDataURL(data[i]);
let oLi = document.createElement("li");
const img = document.createElement("img");
const oProgress = createProgress();
oLi.appendChild(oProgress);
oList.appendChild(oLi);
reader.onload = function () {
img.src = reader.result;
oLi.index = i;
oLi.appendChild(img);
};
reader.onprogress = function (e) {
let per = e.loaded / e.total;
const oProgressBar = oProgress.querySelector(".bar");
oProgressBar.innerHTML = per.toFixed(2) * 100 + "%";
oProgressBar.style.width = per * 300 + "px";
};
reader.onloadend = function (e) {
// oLi.removeChild(oProgress);
};
}
};
//动态创建进度条
function createProgress() {
const oDiv = document.createElement("div");
oDiv.className = "progress";
const oBar = document.createElement("div");
oBar.className = "bar";
oDiv.appendChild(oBar);
return oDiv;
}
};