How to get a progress bar for a file upload with Apache HttpClient 4?

前端 未结 4 1803
暗喜
暗喜 2020-11-29 22:46

I\'ve got the following code for a file upload with Apache\'s HTTP-Client (org.apache.http.client):

  public static void main(String[] args) throws Exception         


        
4条回答
  •  孤城傲影
    2020-11-29 22:58

    A new version using the package org.apache.commons.io.output from commons-io (2.4) and its class CountingOutputStream.

    I changed the initial code to reflect my project needs to use a multipart form as input and the post method (this dues to the requirements imposed by the server side).

    Consider that the delta of large file correspond in my tests to 4096 bytes. This means that the listener method counterChanged() is called every 4096 bytes of transfered data, what is acceptable for my use case.

    The method looks like:

    public void post(String url, File sendFile) {
        HttpParams params = new BasicHttpParams();
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(url + "/" + sendFile.getName());
        MultipartEntity multiEntity = new MultipartEntity(); 
        MyFileBody fileBody = new MyFileBody(sendFile);
    
        fileBody.setListener(new IStreamListener(){
    
            @Override
            public void counterChanged(int delta) {
                // do something
                System.out.println(delta);
            }});
    
        multiEntity.addPart("file", fileBody);
        StringBody stringBody = new StringBody(sendFile.getName());
        multiEntity.addPart("fileName", stringBody);
        post.setEntity(multiEntity);   
        HttpResponse response = client.execute(post);
    }
    

    The class MyFileBody becomes:

    public class MyFileBody extends FileBody {
    
        private IStreamListener listener;
    
        public MyFileBody(File file) {
            super(file);
        }
    
        @Override
        public void writeTo(OutputStream out) throws IOException {
            CountingOutputStream output = new CountingOutputStream(out) {
                @Override
                protected void beforeWrite(int n) {
                    if (listener != null && n != 0)
                        listener.counterChanged(n);
                    super.beforeWrite(n);
                }
            };
            super.writeTo(output);
    
        }
    
        public void setListener(IStreamListener listener) {
            this.listener = listener;
        }
    
        public IStreamListener getListener() {
            return listener;
        }
    
    }
    

    Finally, the listener interface looks like:

    public interface IStreamListener {
    
        void counterChanged(int delta);
    
    }
    

提交回复
热议问题