导入需要使用的jar包
commons-fileupload-xxx.jar
commons-io-xxx.jar 等等
在mvc配置文件中:
<!-- 文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="5400000"/>
</bean>
前端使用表单提交
<form id="Form5" name="Form5" action="<%=basePath%>kh/importFile">
选择上传文件:<input type="file" name="file1" id="file1">
<input type="button" id="imp_btn" οnclick="importFile()" value="导 入">
</form>
在提交之前要先判断提交的文件是否为空,是否为表格,然后ajaxSubmit
$("#imp_btn").attr("disabled",true);
var path = $("#file1").val();
if(path==null || path==""){
alert("请选择上传文件");
$("#imp_btn").removeAttr("disabled");
return false;
}
var okText = /xls|xlsx/; //这里是允许的扩展名
var newFileName = path.split('.'); //这是将文件名以点分开,因为后缀肯定是以点什么结尾的.
newFileName = newFileName[newFileName.length-1];//这个是得到文件后缀,因为split后是一个数组所以最后的那个数组就是文件的后缀名.newFileName.length为当前的长度,-1则为后缀的位置,因为是从0开始的
//开始检查后缀
if (newFileName.search(okText) == -1) {//search如果没有刚返回-1.这个如果newFileName在okText里没有,则为不允许上传的类型. .
alert("上传文件格式必须为表格");//提示
//location.reload();
$("#imp_btn").removeAttr("disabled");
return false;
}
$("#Form5").ajaxSubmit({
type: "Post",
dataType:"jsonp",
//data: $('#Form2').serialize(),
//url:"<%=basePath%>kh/importFile",
async:true,
success:function(result){
result = $.parseJSON(result.replace(/<.*?>/ig,""));
//console.log(result);
//新增成功
if(result.state==1){
alert(result.message);
$("#imp_btn").removeAttr("disabled");
reloadKhInfo();
//window.location.href='<%=basePath %>mobile/week/fotoThirdPage?zbid='+result.data;
// window.event.returnValue=false;
}else{//新增失败
alert(result.message);
$("#imp_btn").removeAttr("disabled");
//$("#imp_btn").removeAttr("disabled");
reloadKhInfo();
return false;
}
},error:function(result){
alert("插入失败");