$.ajaxFileUpload({
type:"post",
url:"importexcel.action?method=importDataByExcel",
//elementIds:["file"],
//data:$("#form1").serialize(),
dataType:'text', //返回值类型
async:false, //同步
secureuri:false, //是否启用安全提交,默认为false
fileElementId:'file', //type="file"的id
success:function(msg){
var data=eval("("+msg+")");
if(data.state=="success"){
window.showModalDialog("gbkh.action?method=jzpp", 'window', "status:true;help:no;status:yes;resizable=yes;center=yes;location=no;dialogWidth=1200px;dialogHeight=700px;");
//window.open("gbkh.action?method=jzpp", "_blank", "scrollbars=yes, resizable=yes,location=no,status=no,center=yes,width=1200px,height=700px");
}else{
alert("Excel排版格式不正确!");
}
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("导入失败");
//alert(XMLHttpRequest.status+","+XMLHttpRequest.readyState+","+textStatus+","+errorThrown);
}
});
3.后台重要代码:
//获取文件路径
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
MultipartFile mufile = multipartRequest.getFile("file");
//文件名带后缀名
String filename = mufile.getOriginalFilename();
//文件名
String filetitle = filename.substring(0, filename.indexOf("."));
String fileurl="";
if (mufile != null) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
// 文件唯一名称
String fileOnlyName = filetitle+sdf.format(new Date())+filename.substring(filename.indexOf("."));
// 文件路径
String filePath = req.getSession().getServletContext().getRealPath("/")+"/PartTimeFile/";
fileurl = filePath + fileOnlyName;
//判断目录是否存在,无则创建
File file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
//判断该文件是否存在
File file2 = new File(fileurl);
if (file2.exists()) {
file2.delete();
}
//转存文件
mufile.transferTo(new File(fileurl));
}
4.ajaxfileupload不支持响应头ContentType为application/json设置,不支持原因可能是为了浏览器兼容,因为ie不支持application/json格式,另外firefox, chrome浏览器iframe在接收application/json格式的时候会自动将其转化为html格式,自动在json数据前后加上<pre></pre>标签导致ajaxfileupload插件取json数据错误
<pre style="word-wrap: break-word; white-space: pre-wrap;">{"message":"上传成功","code":200}</pre>
而spring mvc在处理JSON格式的响应时,会自动将响应头设置为application/json,则导致ajaxfileupload处理报错,所以这里强制将响应头的content-Type设置为text/html;charset=UTF-8,不过这样导致所有使用@ResponseBody注解地方响应头的content-Type都会设置为text/html;charset=UTF-8,无法进行单独的差异化处理。
解决:res.setContentType("text/html;charset=utf-8");
PrintWriter writer =res.getWriter();
JSONObject json=new JSONObject.fromObject(json对象);
writer.write(json.toString());
writer.flush();
wirter.close();
注:ajax中的dataType:'text',否则接受不到json数据