drag
文件拖拽上传
drag
阻止默认事件
//拖拽文件上传默认事件阻止
$(document).on({
dragleave:function(e){
e.preventDefault();
},
drop:function(e){
e.preventDefault();
},
dragenter:function(e){
e.preventDefault();
},
dragover:function(e){
e.preventDefault();
}
});
### drag
拖拽样式改变
var drop_zone = document.getElementById("drop_area");
//文件拖拽上传事件
drop_zone.addEventListener("drop",function (event) {
//拖拽结束后的样式
$("#drop_area").css('border','5px dashed #ccc');
//获取拖拽上传文件
var files = event.dataTransfer.files;
//文件上传处理函数
formHandler(files);
});
window.addEventListener("dragover", function( event ) {
$("#drop_area").css('border','5px dashed #00C0EF');
}, false);
window.addEventListener("dragleave", function( event ) {
$("#drop_area").css('border','5px dashed #ccc');
}, false);
document.getElementById('drop_area').addEventListener('dragover',function (event) {
//阻止默认事件
event.preventDefault();
$("#drop_area").css('border','5px solid #00C0EF');
//阻止事件冒泡
event.stopPropagation();
},false);
文件上传处理函数
function formHandler(fileList) {
formDataInit();
fileRender(fileList);
fileCount();
}
//表单对象初始化
var allFile = [];
var form = document.getElementById("upload-form");
var formData = new FormData(form);
function formDataInit() {
var norm = $("#norm").val();
var major = $("#major").val();
var type = $("#type").val();
formData.set("norm",norm);
formData.set("major",major);
formData.set("type",type);
}
//文件列表渲染
function fileRender(fileList) {
var fileError = 0;
$.each(fileList, function (index, item) {
var fileName = item.name;
var fileEnd = fileName.substring(fileName.indexOf("."));
//判断上传文件格式
if (fileEnd == ".xlsx") {
$("#fileUpload").css('display','inline');
$("#fileDelete").css('display','inline');
//将文件加入allFile中
allFile.push(item);
$('#files').append( '<tr style="padding-top: 7px;">' +
'<td>'+fileName+'</td>' +
'<td>'+(item.size / 1024).toFixed(2)+'K</td>' +
'<td><input type="button" class="btn btn-danger delete" value="取消"></td>' +
'</tr>');
formData.append('UploadForm[excelFiles][]',item);
} else {
fileError++;
}
});
if (fileError > 0) {
alert("只能上传 “.xlsx” 格式的文件!");
}
}
//文件计数
function fileCount() {
var fileCount = $('#files').find('tr').length;
if(fileCount > 0){
$('#fileName').html('共上传 ' + fileCount + ' 个文件');
}else {
$('#fileName').html('您还没有选择文件哦!');
$("#fileUpload").css("display","none");
$("#fileDelete").css("display","none");
}
}
文件取消上传事件
$('#files').on('click','.delete',function (e) {
var saveFile = [];
var deleteName = e.target.parentNode.previousElementSibling.previousElementSibling.textContent;
var deleteIn;
$.each(allFile,function (index, item) {
if(item.name == deleteName){
deleteIn = index;
}else {
saveFile.push(item);
}
});
allFile.splice(deleteIn,1);
//表单数据重置
formData.delete('UploadForm[excelFiles][]');
$.each(saveFile,function (index, item) {
formData.append('UploadForm[excelFiles][]',item);
});
e.target.parentNode.parentNode.remove();
fileCount();
});