1. 程式人生 > >拖拽上傳功能

拖拽上傳功能

else if dev 個數 enum xhr html5 ont align ger

拖拽上傳功能旨在實現拖拽文件或者圖片上傳到你想要保存到的地方。此處上傳的是xml文件,可以在裏面對文件類型進行限制;

聲明:現在的ie瀏覽器9及以下的版本並不支持該方法實現拖拽上傳,如果有大神可以分享ie9及以下的拖拽上傳方法將不勝感激;

代碼:

<body>
<div id="div">
<h1 align="center">拖拽上傳</h1>
<form id="form1" style="margin-left: 20px;" action="<%=path%>/examScore/scoreImport" method="post" enctype="multipart/form-data" onsubmit="return subSelect()">
<div id="datagrid1" style="z-index: 1;" class="formWrap">
<table id="table1" class="table1" border="0" cellspacing="1">
<tr>
<td>拖拽上傳</td>
<td><input class="mini-hidden" name="planId" id="planId"/>
<input onfocus="getPlanList()" id="planName" name="planName" class="mini-textbox" required="true" width="96%"/><font color="red">*</font>
</td>
<td width="130px;"><input onclick="showAddPlan()" class="input-flat" type="button" value="新增"/></td>
</tr>
<tr>
<td>導入文件</td>
<td>
<input type="file" name="doc" id="doc" style="display:none" onchange="selectFile()"/>
<input type="button" id="btn" onclick="document.getElementById(‘doc‘).click()" value="瀏覽"/>
<input name ="filename" id="filename" value=""/>
<!-- <input type="file" name="upload" /> -->

</td>
<td width="130px;"></td>
</tr>
</table>

<div id="preview" class="preview" name="upload" ></div>
<div id="planList" style="display: none;z-index: 2;position: absolute;left:42%;height:80%;top:20%;">
<iframe src="<%=basePath %>examPlan/showPlanList" id="planFrame" frameborder="0"
style="width:120%;height:320px;border=0;overflow: scroll;"></iframe>
</div>

<div id="addPlan" style="display: none;z-index: 2;position: absolute;left:1px;top:1px;">
<iframe src="<%=basePath %>examPlan/showAddPlan" id="addPlanFrame" frameborder="0"
style="width:780px;height:440px;border=0;overflow: scroll;"></iframe>
</div>
<table class="table2" style="margin-top: 100px;">
<tr>
<td style="border: none; text-align: center;">
<input id="sub" class="input-flat" type="button" onclick="mySubmit();"
value="提交"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
class="input-flat" type="button" onclick="onCancel()" value="取消"/>
</td>
</tr>
</table>

</div>
</form>
</div>
<script type="text/javascript">
var fileList="";
//1、文件上傳HTML5 通過drag把文件拖拽到瀏覽器的默認事件覆蓋
//文件離開
document.ondragleave=function(e){
e.preventDefault();
console.info("文件離開執行了我!!");
};
//鼠標松開文件
document.ondrop=function(e){ debugger
e.preventDefault();
console.info("松開以後執行了我!");
};
//鼠標移動文件
document.ondragover=function(e){
e.preventDefault();
console.info("文件移動以後執行了我!");
};

function tm_upload(){
var img1="";
var img2="";
var uploadArea=document.getElementById("div");
//2、通過HTML5拖拽事件,ondrop,然後通過拖動區域監聽瀏覽器的drop事件達到文件上傳的目的
uploadArea.addEventListener("drop", function(e){
e.preventDefault();
//3、從事件event中獲取拖拽到瀏覽器的文件信息 ,如果沒有文件個數的限制可以註釋掉此段代碼。
var fileNum= document.getElementById("preview").childNodes.length
if(fileNum>0){
alert("只能上傳一個文件")
return false;
}

    //此處是ie9及以下不支持的方法的地方;e.dataTransfer.files獲取不到。
fileList=e.dataTransfer.files;
for(var i=0;i<fileList.length;i++){
//此處判斷只能上傳圖片
if(fileList[i].name.indexOf(".xls")<0){
alert("請上傳excle文件");
return;
}
//圖片預覽 這一步需要判斷是什麽瀏覽器 大家自己判斷吧
/*************************************/
// img1=window.URL.createObjectURL(fileList[i]);
img1="../app/img/xlsIMG11.png";//我在此處給引入的 文件配置了一張文件類型的圖標
img2="../app/img/deleteIMG11.png";
function deleteFile(){
document.getElementById("preview").innerHTML ="";
fileList=null;
}
/*************************************/
var str="<div><img src=‘"+img1+"‘/><p>"+fileList[i].name+"</p><button onclick=‘deleteFile()‘>刪除</button></div>";
var str1=fileList[i].name;
document.getElementById("preview").innerHTML +=str;
// document.getElementById("preview").value=str1;
var fileName=fileList[i].name;
console.info(fileName);
var fileSize=fileList[i].size;
console.info(fileSize);
document.getElementById("filename").value=fileName;
//4、通過XMLHttpRequest上傳文件到服務器 就是一個ajax請求
}
});
}
//直接調用
tm_upload();
function deleteFile(){
document.getElementById("preview").innerHTML ="";
document.getElementById("filename").value="";
}

function subSelect(){ debugger
if( document.getElementById("filename").value==""){
fileList.length=0
alert("選擇文件不能為空")
return false;
}

var FileIsNull = document.getElementById("doc").value;
var length =fileList.length;
if(FileIsNull==null||FileIsNull==""){
for(var j=0 ; j<length;j++){
//此處判斷只能上傳圖片
if(fileList[j].name.indexOf(".xls")<0){
alert("請上傳.xls文件");
return;
}
//圖片預覽 這一步需要判斷是什麽瀏覽器 大家自己判斷吧
/*************************************/
//img1=window.URL.createObjectURL(fileList[i]);


/*************************************/
//var str="<div><img src=‘"+img1+"‘/><p>"+fileList[j].name+"</p></div>";
//var str1=fileList[j].name;
// document.getElementById("preview").innerHTML +=str;
// document.getElementById("preview").value=str1;
var fileName=fileList[j].name;
console.info(fileName);
var fileSize=fileList[j].size;
console.info(fileSize);
//4、通過XMLHttpRequest上傳文件到服務器 就是一個ajax請求
var xhr=new XMLHttpRequest();
//5、這裏需要先寫好一個importExcel.jsp的上傳文件,當然,你寫成servlet或者是action都可以
xhr.open("post","<%=path%>/examScore/scoreImport",true);
xhr.setRequestHeader("X-Request-Width", "XMLHttpRequest");
//6、通過HTML5 FormData動態設置表單元素
var formData=new FormData();//動態給表單賦值,傳遞二進制文件
//其實就相當於<input type="file" name="file"/>
formData.append("upload",fileList[j]);
xhr.send(formData);
return false;
}
}else{
return true;
}
};
mini.parse();



/* var file=$(":file").val();
if(""==file){
alert("文件不能為空");
return false;
} */
/* var pos = file.lastIndexOf(‘.xls‘);
var pos1=file.lastIndexOf(‘.xlsx‘);
if(pos==-1&&pos1==-1){
alert("文件類型不匹配");
return false;
}

if(pos + 4 != file.length&&pos1+5!=file.length){
alert("文件類型不匹配");
return false;
} */
//3、從事件event中獲取拖拽到瀏覽器的文件信息
/* var fileNum= document.getElementById("preview").childNodes.length
if(fileNum>0){
alert("只能上傳一個文件")
return false;
} */


function showAddPlan(){
$("#table1").hide();
$("#addPlan").show();
}
function getPlanList(){
var planSort=‘<%=planSort%>‘;
var url="<%=path %>/examPlan/showPlanList?planSort=<%=planSort%>";
mini.open({
url: url,
title: "計劃名稱列表", width: 800, height: 450,
ondestroy: function (action) {
}
});
}
function onCancel() {
window.CloseOwnerWindow("ok");
}
</script>
<script type="text/javascript">
mini.parse();
function beforeSubmit(){
var file=$(":file").val();
if(""==file){
alert("文件不能為空");
return false;
}
var pos = file.lastIndexOf(‘.xls‘);
var pos1=file.lastIndexOf(‘.xlsx‘);
if(pos==-1&&pos1==-1){
alert("文件類型不匹配");
return false;
}
if(pos + 4 != file.length&&pos1+5!=file.length){
alert("文件類型不匹配");
return false;
}
}
function onCancel() {
window.CloseOwnerWindow("ok");
}
function mySubmit(){
$("#form1").submit();
window.CloseOwnerWindow("ok");
}
</script>
</body>

後臺你們自己寫吧,你們用什麽框架我有不知道,只要接收一下這裏傳過去的xml文件就行了,我用的spring_mvc框架所以在後臺接收是這樣的

註意:標註部分是框架接收文件類型的必備註解,

public void scoreImport(@RequestParam("upload") MultipartFile mFile, Model model, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
StaticEntity.setPagestatus(3);// 3代表jsp頁面可關閉
InputStream is = excelUtil.processFileUpload(mFile, request);
Map map = new HashMap();
map = readScoreExcelData(is, map);
try {
if (map.get("content") != "") {
StaticEntity.setPagestatus(2);
} else {
List lists = (List) map.get("lists");
String planId=map.get("planId").toString();
String status=scoreService.getPlanStatus(planId);
if(status==null||status==""){
StaticEntity.setPagestatus(4);//計劃不存在
}else if("1".equals(status)){
StaticEntity.setPagestatus(5);//計劃已發布成績
}else{
request.setAttribute("planId", planId);
scoreService.insertScoreData(lists, request);// 縣
StaticEntity.setPagestatus(1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

拖拽上傳功能