我有一個將一個或多個檔案上傳到 servlet 的 Ajax POST 呼叫。
在我的 servlet 中,我使用 Commons FileUpload 庫來管理上傳檔案的程序:
private RequestInfo getRequestInfoMultipart(HttpServletRequest request, HttpSession session) throws SupportException {
RequestInfo multipartReqestInfo = new RequestInfo();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(TMP_DIR));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_SIZE_UPLOADED_FILE);
List<FileItem> items = upload.parseRequest(request); // <-- Throws exception on max file size reached
...
} catch (FileUploadException e) {
throw new SupportException("SOP_EX00009");
} catch (Exception e) {
throw new SupportException("SOP_EX00001", e);
}
}
當我在 getRequestInfoMultipart 方法之外捕獲例外時,我在 http 回應中撰寫了一個帶有兩個引數(結果和訊息)的 JSon 物件:
private RequestInfo getRequesInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session, boolean isMultipart) {
try {
if (isMultipart) {
return getRequestInfoMultipart(request, session);
}
return getRequestInfo(request, session);
} catch (SupportException e) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try (PrintWriter writer = response.getWriter()) {
JSonResult jsonResult = new JSonResult();
jsonResult.setResult(KO);
jsonResult.setMessage(e.getMessage());
writer.print(new Gson().toJson(jsonResult));
writer.flush();
} catch (IOException ex) {
log.error("Error getting PrintWriter", ex);
}
return null;
}
}
之后,Ajax 呼叫應該在成功塊中獲得回應,但是,http 請求被重復,然后 Ajax 呼叫進入錯誤塊,所以我無法向用戶顯示結果,而是通用錯誤訊息。
有誰知道為什么重復請求以及為什么 Ajax 呼叫以錯誤結束?
非常感謝你。奎克。
uj5u.com熱心網友回復:
最后我發現了錯誤,它與 Ajax 或 servlet 代碼無關,而是與 Tomcat 默認連接器 maxSwallowSize 屬性有關:
當有人上傳 Tomcat 知道的檔案大于允許的最大大小時,Tomcat 會中止上傳。然后,Tomcat 不會吞下主體,客戶端不太可能看到回應。因此,似乎請求被重復,最后發生連接重置,ajax 收到 0 錯誤代碼并且沒有來自 servlet 的資訊。
在開發中,您可以在 server.xml 檔案中使用 -1 值將屬性設定為無限制:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxSwallowSize="-1" />
在生產中,您必須為您的興趣設定一個適當的值。
這樣做,服務器將在處理來自客戶端的所有正文后回應。但請記住,如果客戶端上傳的檔案大于 maxSwallowSize,您將獲得相同的行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476471.html
