2016-09-14 107 views
0

基本上我有一個客戶端文件上傳,可用於上傳文件到服務器,並在我的服務器端,我有有限的文件大小使用MultipartConfig至5MB,如果文件已超出限制,我需要中止上傳處理。如何在java服務器上中止文件上傳?

服務器端:

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, 
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5) 


public void doPost(HttpServletRequest request, 
     HttpServletResponse response) throws IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter() ; 
    try{ 
     MultipartRequest multipartRequest = new MultipartRequest(request, "D:\\"); 
    } catch(IOException e){ 
     System.out.println(e.getMessage()); 
     return; 
    } 
    out.print("Successfully Uploaded"); 
} 

FYI:我有我的@MultipartConfig了我的課

的正如你可以看到我有一個try and catch其中,如果該文件的限制已經超過拋出一個異常,說有關文件超過異常,在這裏我需要中止上傳過程,併發送一個簡單的錯誤給客戶端,超過了限制。

+0

所以呢?使用該響應來發送合適的狀態代碼以及任何您想要的內容。 – Kayaman

+0

'sendError'是一個快捷方法。 – RealSkeptic

+0

好吧,我剛剛發現,對於我的情況'httpError 409'是一個合適的錯誤,我試着把'response.sendError(response.SC_CONFLICT,「文件限制已超過」);'在我的'catch'但是沒有奏效 – darees

回答

-1

您可以使用httpget.abort()來中止/取消請求。

public class ClientAbortMethod { 

    public final static void main(String[] args) throws Exception { 
     CloseableHttpClient httpclient = HttpClients.createDefault(); 
     try { 
      HttpGet httpget = new HttpGet("http://httpbin.org/get"); 

      System.out.println("Executing request " + httpget.getURI()); 
      CloseableHttpResponse response = httpclient.execute(httpget); 
      try { 
       System.out.println("----------------------------------------"); 
       System.out.println(response.getStatusLine()); 
       // Do not feel like reading the response body 
       // Call abort on the request object 
       httpget.abort(); 
      } finally { 
       response.close(); 
      } 
     } finally { 
      httpclient.close(); 
     } 
    } 

} 

Refer this