近期要在前台jsp页面添加一个excel文件导入的功能,用input的file可以实现。下面为具体操作
jsp代码
<input id="addfile" name="addfile" type="button" class="button_01" value="导入Excel" onclick="javascript:openBrowse();" />
<input id="file" name="file" type="file" accept="application/vnd.ms-excel" style="width: 0px;"/>
<input type="text" id="filename"style="display:none;"/>
直接从input file获取路径是不完整的,因为浏览器为了安全把input file的路径进行了隐藏,一般的方法是无法获取完整路径的,需要对IE和火狐做相关处理。为了美观,将input file的width设置为0px,这样前台显示的就只有一个导入按钮。
js代码
//filename处理,如果不作处理的话ie自动传输到后台的路径不是绝对路径
function openBrowse(){
var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false;
if(ie){
document.getElementById("file").click();
var obj=document.getElementById("file");
obj.select();
var path=document.selection.createRange().text;
document.getElementById("filename").value=path;
//alert(path);
importExcel($("#filename").val());
}else{
var a=document.createEvent("MouseEvents");//FF的处理
a.initEvent("click", true, true);
document.getElementById("file").dispatchEvent(a);
}
}<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
//excel导入
function importExcel(filename){
//alert(filename);
var turl = "你的后台访问路径" ;
var url = "&type=importExcel&filename="+filename;
turl = turl + url;
turl = encodeURI(turl);
if(filename == '' || filename.length==0){
return false;
}
var lyr=layer.load('正在执行中,请稍候......');
window.location.href = turl;
}
OK,input file的文件上传代码已经完成,我在项目中运行没有问题的。