今天寫的一個下載功能發現了一個問題:
這個下載的功能是將前臺獲取的數據傳遞到後臺之後下載成excel文件,我就寫了一個方法:
window.location.href = $("#basePath").val() + "purPlan/exportDetail.do?details="+ encodeURI(JSON.stringify(details));
其中details就是要傳遞的數據,我把它編碼之後傳到後臺進行處理。
本來數據量不大的時候是沒有問題的,然後寫了幾百條數據進去了之後下載就出現問題了。點擊下載一直未響應。
百度之後發現:通過url傳遞數據使用的是get方式,是有大小限制的。很多文章都說GET方式提交的數據最多隻能是1024字節。
而實際上,URL不存在參數上限的問題,HTTP協議規範也沒有對URL長度進行限制。這個限制是特定的瀏覽器及服務器對它的限制。IE對URL長度的限制是2083字節(2K+35字節)。對於其他瀏覽器,如FireFox,Netscape等,則沒有長度限制,這個時候其限制取決於服務器的操作系統。即如果url太長,服務器可能會因爲安全方面的設置從而拒絕請求或者發生不完整的數據請求。
而使用post傳遞數據理論上是沒有限制的。
所以,在url中傳遞數據,如果傳遞的數據過多,就可能會發生錯誤。
因此直接在下載的url中傳遞大量數據是不可行的。
所以我做了如下修改:
//前臺
$.ajax({
url : "purPlan/postDetailsData.do",
type : "post",
dataType : "json",
data : {
details : JSON.stringify(details)
},
success : function(data){
if(data && data.success){
window.location.href = $("#basePath").val() + "purPlan/exportDetail.do";
}else{
$.dialog.alert("出現問題!");
}
}
});
//後臺
@RequestMapping("/postDetailsData.do")
public void postDetailsData(HttpServletRequest request,HttpServletResponse response,HttpSession session,String details){
session.setAttribute("details", details);
this.writeJson(response, new AjaxMsg(true,"傳遞數據成功"));
}
@RequestMapping(value = "/exportDetail.do")
public void exportDetail(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
String details = (String) session.getAttribute("details");
//將明細字符串轉化爲fmodel
List<FPurPlanDetail> detailList = JsonParse.getList(details , FPurPlanDetail.class);
ExportHelp.compatibleFileName(request, response, "物資導出");
PurPlanExport.exportExcel(response,detailList);
}
先使用ajax的post方式將數據傳送到後臺,將數據保存到session中,在訪問下載數據的url,從session中獲取數據然後進行處理、下載。這樣可以避免出現問題。