<!DOCTYPE html>
<html>
<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>Picture Bed</title>
</head>
<body>
<div style="margin:30px;">
<div id="fileData">
<input type="file" accept="image/*">
<input type="submit" value="Upload" onclick="upload()">
</div>
<div id="outData" style="margin-top:30px;word-wrap:break-word;"></div>
</div>
<script>
var state = false;
var file = null;
//粘贴事件
document.addEventListener('paste', function(event) {
var items = event.clipboardData && event.clipboardData.items;
if (items && items.length) {
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
//上传文件
upload();
}
});
//上传事件
function upload() {
if(state == true) {
alert('正在上传文件');
return;
}
let fileDom = document.querySelector('input[type=file]');
let submitDom = document.querySelector('input[type=submit]');
let outDom = document.querySelector('#outData');
//锁定元素
state = true;
submitDom.disabled = true;
//表单提交文件
const formData = new FormData();
if (file == null) file = fileDom.files[0];
formData.append('file', file);
var request = new XMLHttpRequest();
request.onreadystatechange = function(event) {
if (request.readyState == 4 && request.status == 200) {
var resultText = request.responseText;
var result = JSON.parse(resultText);
var outMsg = "";
if (result.state == true) {
outMsg = result.data;
} else {
outMsg = result.msg;
}
outDom.innerHTML += `${outMsg}<br /><br />`;
file = null;
state = false;
submitDom.disabled = false;
}
};
request.open("POST", "");
request.send(formData);
}
</script>
</body>
</html>
|