如何在java服务器中中止文件上传?

时间:2016-09-14 15:25:21

标签: java

基本上我有一个客户端文件上传,可用于将文件上传到服务器,在我的服务器端,我使用MultipartConfig到5MB的文件大小有限,如果文件超出限制我需要中止上传过程。

服务器端:

@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");
}

仅供参考:我的班级@MultipartConfig

正如你所看到的,我有一个try and catch,如果超出文件限制会抛出一个异常,说明文件超出异常,这里我需要中止上传过程,并向客户端发送一个简单的错误限制已经超过了。

1 个答案:

答案 0 :(得分:-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