JQuery代码:
$("#upload").click(function () {
$.ajaxFileUpload
(
{
url: "<%=path%>/cdc/upload/"+$('#categoryId').val(), //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'file', //文件上传域的ID
dataType:'text', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
parent.layer.msg(jQuery.parseJSON($(data).text()).message,{icon: 6,time:1000});
setTimeout("parent.location.reload()", 1000);
},error: function (data, status, e)//服务器响应失败处理函数
{
parent.layer.msg('上传文件失败!',{icon: 5,time:1000});
}
}
)
});
ps:1、这里用到的url传参为springMvc中Constrol的一种!
2、多次亲测使用type:''post,data{}传参后台获取为null
ps:使用$.ajaxFileUpload()上传文件时,设置dataType为json,执行成功后无法调用success,目前不知道为什么,实在没办法最后将设置dataType为text,执行成功后回调success函数,但返回时data为<pre style="...">后台返回值</pre>,在使用jQuery.parseJSON($(data).text()).message得到后台返回的map对象的message值
ps:jQuery.parseJSON($(data).text()).message,$(data).text()获得标签中的值,jQuery.parseJSON()封装为json对象,最后在获取到json中message值。
后台java代码:
<span style="white-space:pre"> </span>/**
* @author 王超
* @param file 文件
* @return 返回结果消息
* @throws IOException 写入文件异常
* @throws FileUploadException
*/
@RequestMapping(value="/upload/{categoryId}", method=RequestMethod.POST)
@ResponseBody
public Object uploadDB(HttpServletRequest request,
@RequestParam("dbfile") CommonsMultipartFile file,
@PathVariable String categoryId) {
HttpSession session =request.getSession();
UserServiceDTD user =(UserServiceDTD)session.getAttribute("userinfo");
return cds.uploadDB(file,user.getId(),Integer.parseInt(categoryId));
}
ps:代码在使用$("#upload").click()点击事件,可以正常使用,但是在和jQuery的Validform验证配合使用仍然无法调用success,进行提示。我在这时候也做了一些处理可以在保证系统正常下给用户一个友好的提示。
ps:推荐使用,from表单异步提交ajaxSubmit相对比这个完善点,强大点。