下面是ajax代码和Controller层代码,期初以为是后台程序写错了。
$("#sourcefile").ajaxSubmit({ type: "post", dataType: "json", // 'xml', 'script', or 'json' (expected server response type) url: "/springMVC/upload/up", success: function (result) { if (result) { alert(result.col0); } }, error:function(data, XMLHttpRequest, textStatus, errorThrown){ alert(1); } });
@RequestMapping(value="/upload/up") public @ResponseBody ExcelName upload(@RequestParam("sourceFile") MultipartFile sourceFile, HttpServletRequest request, ModelMap model,HttpServletResponse response) { //判断文件是否为空 if (sourceFile==null) return null; //获取文件名 String name=sourceFile.getOriginalFilename(); System.out.println("name"); //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null) long size =sourceFile.getSize(); if (name==null ||("").equals(name) && size==0) return null; //批量导入。参数:文件名,文件。 List<ExcelName> cpolicyList = ExcelUtils.batchImport(name,sourceFile); //迭代添加信息(注:实际上这里也可以直接将cpolicyList集合作为参数,在Mybatis的相应映射文件中使用foreach标签进行批量添加。) for( ExcelName customer:cpolicyList){ colDataService.insertData(customer); } ExcelName e1=new ExcelName(); e1.setCol0("success"); return e1;}
后打点跟踪后台发现,原来因为上传按键type写成了submit导致提交了一次action,致使ajax未获取到返回结果走了error。
下面是修改正确后的jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>上传</title><script type="text/javascript" src="./jquery-3.1.1.js"></script><script type="text/javascript" src="./jquery.form.js"></script><script type="text/javascript"> function submitImport(){ var epath = $('#source_file').val(); if(epath==""){ alert( '导入文件不能为空!'); return; } if (epath.substring(epath.lastIndexOf(".") + 1).toLowerCase()!="xlsx") { alert( '导入文件类型必须为excel!'); return; } $("#sourcefile").ajaxSubmit({ type: "post", dataType: "json", // 'xml', 'script', or 'json' (expected server response type) url: "/springMVC/upload/up", success: function (result) { if (result) { alert(result.col0); } }, error:function(data, XMLHttpRequest, textStatus, errorThrown){ alert(1); } }); } //partExportfunction downloadTemplate() { document.sourcefile.action = "/springMVC/upload/partExport"; form.submit(); //表单提交 } </script></head><body><div> <form id="sourcefile" name="sourcefile" action="" method="post" enctype="multipart/form-data"> <input type="button" value="添 加" onClick="addAirLine()" /> <input style="margin-left: 20px;" id="source_file" name="sourceFile" type="file" value="选择文件" /> <input style="margin-left: 20px;" data-loading-text="请勿重复提交" type="button" value="上 传" onClick="submitImport()"> <input style="margin-left: 20px;" type="submit" value="下载模板" onClick="downloadTemplate();"> </form> </div></body></html>
新闻热点
疑难解答
图片精选