在效果出来之后请务必检查同一个被拖拽的文件的内容修改之后,上传的文件是否也修改了
<!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">
<title>Document</title>
<script src="axios.min.js"></script>
</head>
<body>
<img id="img" src="" alt="">
<div name="image" id="dropbox" style="min-width:300px;min-height:200px;border:3px dashed silver;"></div>
<script>
// 目标元素中dragover和drop事件中要阻止默认行为(拒绝被拖放),否则拖放不能被实现
dropbox.addEventListener("dragover", function (e) {
e.preventDefault();
});
dropbox.addEventListener("drop", function (e) {
e.preventDefault();
let file = e.dataTransfer.files[0]
console.log('文件类型是: ', file.type)
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadstart = function(e) {
console.log(reader.result)
console.log("开始加载")
}
reader.onprogress = function(e) {
console.log(e.total)
}
reader.onload = function() {
console.log(reader.result)
img.src = reader.result
}
reader.onloadend = function(e) {
if (reader.error) {
console.log('加载失败: ', reader.error);
} else {
let form_data = new FormData()
form_data.append('photo', file)
//上传没有错误,ajax发送文件,上传二进制文件
axios({
url: 'http://hostname/api/test',
method: 'post',
data: form_data
}).then(res => {
console.log(res)
})
}
}
});
</script>
</body>
</html>
``
网友评论