<--html-->
<div id="box" style="width: 200px; height: 100px; border: dashed 1px; text-align: center; padding-top: 36px; float:left; margin-right: 15px;">
请将文件拖拽到此区域
</div>
<--JS-->
<script>
window.onload = function () {
var xhr = new XMLHttpRequest();
var dz = document.getElementById('box');
function uploadFile(formData) {
xhr.open('POST', '上传接口地址', true);
xhr.send(formData);
xhr.onreadystatechange = ajaxFun;//设置响应回调函数
}
function ajaxFun() {
if (xhr.readyState == 4 && xhr.status == 200) {
var b = xhr.responseText;
if (b) {
$("#preview").append(b);
}
}
}
dz.ondragenter = function () {
dz.innerHTML = '请释放鼠标';
};
dz.ondragover = function () {
dz.innerHTML = '+';
};
dz.ondragend = function () {
dz.innerHTML = '+';
};
dz.ondragleave = function () {
dz.innerHTML = '请将文件拖拽到此区域';
};
dz.ondragover = function (ev) {
//阻止浏览器默认打开文件的操作
ev.preventDefault();
this.className = 'over';
};
dz.ondrop = function (ev) {
this.className = '';
//阻止浏览器默认打开文件的操作
ev.preventDefault();
//表单上传文件
var formData = new FormData();
formData.append('photoimg', ev.dataTransfer.files[0]);
uploadFile(formData);
dz.innerHTML = '请将文件拖拽到此区域';
}
};
</script>