Android 大文件上傳時,處理上傳進度問題

openkk 12年前發布 | 63K 次閱讀 Android Android開發 移動開發

進行大文件上傳時,顯示上傳進度是很好的用戶體驗,可以有效的緩解用戶急躁的情緒。今天Android IT 分享一個好的顯示上傳進度的解決方案。

 Android 大文件上傳時,處理上傳進度問題

我們用到以下兩個類就可實現帶進度條的文件上傳:

1、CustomMultiPartEntity extends MultipartEntity, 

2、HttpMultipartPost extends AsyncTask

代碼如下:

 import java.io.FilterOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;

import org.apache.http.entity.mime.MultipartEntity;



public class CustomMultipartEntity extends MultipartEntity {

    private final ProgressListener listener;

    public CustomMultipartEntity(final ProgressListener listener) {

        super();

        this.listener = listener;

    }

    public CustomMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener)     {

        super(mode);

        this.listener = listener;

    }

    public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,

            final Charset charset, final ProgressListener listener) {

        super(mode, boundary, charset);

        this.listener = listener;

    }

    @Override

    public void writeTo(final OutputStream outstream) throws IOException {

        super.writeTo(new CountingOutputStream(outstream, this.listener));

    }

    public static interface ProgressListener {

        void transferred(long num);

    }



    public static class CountingOutputStream extends FilterOutputStream {

        private final ProgressListener listener;

        private long transferred;

        public CountingOutputStream(final OutputStream out, final ProgressListener listener) {

            super(out);

            this.listener = listener;

            this.transferred = 0;

        }

        public void write(byte[] b, int off, int len) throws IOException {

            out.write(b, off, len);

            this.transferred += len;

            this.listener.transferred(this.transferred);

        }

        public void write(int b) throws IOException {

            out.write(b);

            this.transferred++;

            this.listener.transferred(this.transferred);

        }

    }

}

該類計算寫入的字節數,我們需要在實現ProgressListener中的trasnfered()方法,更行進度條



public  class HttpMultipartPost extends AsyncTask<HttpResponse, Integer, TypeUploadImage> {



    ProgressDialogpd;



    longtotalSize;



    @Override

    protectedvoidonPreExecute(){

        pd= newProgressDialog(this);

        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        pd.setMessage("Uploading Picture...");

        pd.setCancelable(false);

        pd.show();

    }



    @Override

    protectedTypeUploadImagedoInBackground(HttpResponse... arg0) {

        HttpClienthttpClient = newDefaultHttpClient();

        HttpContexthttpContext = newBasicHttpContext();

        HttpPosthttpPost = newHttpPost("http://herpderp.com/UploadImage.php");



        try{

            CustomMultipartEntitymultipartContent = newCustomMultipartEntity(

                    newProgressListener() {



                        @Override

                        public void transferred(longnum){

                            publishProgress((int) ((num / (float) totalSize) * 100));

                        }

                    });



            // We use FileBody to transfer an image

            multipartContent.addPart("uploaded_file", newFileBody(

                    newFile(m_userSelectedImagePath)));

            totalSize= multipartContent.getContentLength();



            // Send it

            httpPost.setEntity(multipartContent);

            HttpResponseresponse = httpClient.execute(httpPost, httpContext);

            String serverResponse = EntityUtils.toString(response.getEntity());



            ResponseFactoryrp = newResponseFactory(serverResponse);

            return(TypeImage) rp.getData();

        }



        catch(Exception e) {

            System.out.println(e);

        }

        returnnull;

    }



    @Override

    protectedvoidonProgressUpdate(Integer... progress){

        pd.setProgress((int) (progress[0]));

    }



    @Override

    protectedvoidonPostExecute(TypeUploadImageui) {

        pd.dismiss();

    }

}

在 transferred()函數中調用publishProgress((int) ((num / (floattotalSize) * 100));

在onProgressUpdate()實現上傳進度的更新操作

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!