2016-09-14 105 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