Android 大文件上传时,处理上传进度问题

进行大文件上传时,显示上传进度是很好的用户体验,可以有效的缓解用户急躁的情绪。今天Android IT 分享一个好的显示上传进度的解决方案。

Android 大文件上传时,处理上传进度问题_第1张图片

我们用到以下两个类就可实现带进度条的文件上传:

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 {
    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);
        }
        return null;
    }
    @Override
    protectedvoidonProgressUpdate(Integer... progress){
        pd.setProgress((int) (progress[0]));
    }
    @Override
    protectedvoidonPostExecute(TypeUploadImageui) {
        pd.dismiss();
    }
}

在 transferred()函数中调用publishProgress((int) ((num / (floattotalSize) * 100));

在onProgressUpdate()实现上传进度的更新操作



你可能感兴趣的:(【Android】)