jsp:
<h4>或者将文件拖拽到这里</h4>
<div class="upload-drop-zone" id="drop-zone">将文件拖拽到这里</div>
css:
<style>
/* layout.css Style */
.upload-drop-zone {
height: 200px;
border-width: 2px;
margin-bottom: 20px;
}
/* skin.css Style*/
.upload-drop-zone {
color: #ccc;
border-style: dashed;
border-color: #ccc;
line-height: 200px;
text-align: center
}
.upload-drop-zone.drop {
color: #222;
border-color: #222;
}
</style>
js:
<!-- 拖拽上传 -->
<script type="text/javascript">
var $dropZone = $("#drop-zone");
// drag进入事件
$dropZone[0].addEventListener('dragenter', function () {
$dropZone.addClass("drop");
$dropZone.html("松手完成上传");
}, false);
// drag移出事件
$dropZone[0].addEventListener('dragleave', function () {
$dropZone.removeClass("drop");
$dropZone.html("将文件拖拽到这里");
}, false);
// 松鼠标事件
$dropZone[0].addEventListener("drop", function(e) {
//取消默认浏览器拖拽效果
e.preventDefault();
var fileList = e.dataTransfer.files;
//$("#up_text").val(fileList[0].name);
//alert(fileList[0].type);
upload(fileList[0]);
}, false);
function upload(file){
if(!checkType(file)) return;
var _this = this;
var fd = new FormData();
fd.append('file', file);
var lay;
$.ajax({
type : "POST",
dataType : "json", // 服务器返回的数据类型
contentType : false, // 禁止设置请求类型
processData : false, // 禁止jquery对DAta数据的处理,默认会处理
async : false,
cache : false,
url : "/cdps/admin/students/import",
data : fd,
beforeSend : function() {
lay = layer.load(2, {
shade : [ 0.5, '#666c7f' ]
});
},
complete : function(xhr, status) {
layer.close(lay);
recoverState();
},
success : function(result) {
},
error : function() {
}
});
}
// 校验格式
function checkType(file){
var _fileDir = file.name;
var _suffix = _fileDir.substr(_fileDir.lastIndexOf("."));
if ("" == _fileDir) {
layer.msg('没有选择文件!', function() {
//关闭后的操作
recoverState();
});
return false;
}
if (".xls" != _suffix && ".xlsx" != _suffix) {
layer.msg('文件格式有误!请选择 Excel 文件!', function() {
//关闭后的操作
recoverState();
});
return false;
}
return true;
}
function recoverState(){
$dropZone.removeClass("drop");
$dropZone.html("将文件拖拽到这里");
}
$(document).on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); });
$(document).on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); });
$(document).on('drop', function (e) { e.stopPropagation(); e.preventDefault(); });
</script>
效果图:
file的属性详解 https://www.cnblogs.com/xuzhudong/p/8926356.html
参考: https://www.cnblogs.com/wyb666/p/9740731.html
https://www.cnblogs.com/wyb666/p/9740731.html