说明:该案列是基于Ajax、SpringMVC进行的,Excele操作采用POI方式,主要目的在于分享在功能实现过程中遇到的各种问题及解决方法。
1、input标签file类型获取选择文件完整路径(直接以.value方式获取到的路径不是完整路径):
function getFullPath(obj) {
if (obj) {
//Internet Explorer
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
obj.select();
return document.selection.createRange().text;
}
//Firefox
else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
传入参数为input对象
获取:var filepath = getFullPath(fileObj);//文件路径包括文件名
2、路径由jsp页面到后台的乱码问题:
选择的文件的完整路径中会包含中文,如果不进行处理传到后台会出现中文乱码。
解决方式:在jsp页面对路径进行两次编码,在后台再进行解码。
两次编码:var file = encodeURI(encodeURI(filepath));//解决文件路径乱码
后台解码:String file = request.getParameter("file");
file = URLDecoder.decode(file, "UTF-8");
3、Ajax发起请求(也可以采用其它方式发起请求):
$.ajax({
async : false,
cache:false,
type: 'POST',
dataType : "text",
url: "<%=request.getContextPath()%>/queryService/importdata/importfile?sjlx="+sjlx+"&file="+file,
error: function() {//请求失败处理函数
alert('导入数据发生异常!');
},
success:function(data){ //请求成功后处理函数
if(data =="" || data == null){
alert('数据导入成功!');
}else{
alert(data);
}
}
});
注意:dataType类型应该与后台返回的数据类型保持一致,否则会报错。
4、判断选择文件的文件格式:
var file = document.getElementById("drfile").value;//文件路径包括文件名
var fileext = file.replace(/.+\./,"");//获取选中的文件的格式
if(fileext!="xls"&&fileext!="xlsx"){
alert("请选择正确的格式的文件!");
return false;
}
5、
jsp页面:
<div id="root" class="easyui-layout" data-options="fit:true" style="padding:4px">
<div id="filter" data-options="region:'north',title:'数据导入'" data-bind="show:elements.length>0" style="padding:8px;background-color:#F9F7F4; height:150px" >
<ntais:form action="/login.do?method=login">
<table width="100%" cellpadding="0" cellspacing="4">
<tr>
<td class="td_title" align="right" width="15%">数据类型:</td>
<td class="td_normal" width="35%">
<ntais:codeList codeListName="T_SYS_DRDZB" catalog="" id="DRID" name="string(SJLXMC)" defaultshow="--请选择--" style="width: 60%;" >
</ntais:codeList>
<span style="color:red">*</span>
</td>
<td class="td_title" align="right" width="15%">选择文件:</td>
<td class="td_normal" width="35%">
<input type="file" id="drfile" style="width: 60%;"/>
<a href="#" οnclick="download()">模板下载</a>
</td>
</tr>
<tr>
<td class="td_normal" align="right" colspan="2">
<input type="button" id="dr" value="导入" οnclick="importfile()" class="button_normal"/>
<input type="button" id="qk" value="清空