How to show progress bar status by percentage while uploading json data?

前端 未结 5 1435
旧巷少年郎
旧巷少年郎 2020-12-20 15:55

I am uploading string and photo.and its working fine. Now I want to show progress bar while uploading data with percentage but percentage show very quickly to 100 percentage

5条回答
  •  粉色の甜心
    2020-12-20 16:40

    Take a look at this gist, there you can find full working exaple

    First you have to create a custom RequestBody with an interface witch will update your progress bar.

    import com.squareup.okhttp.MediaType;
    import com.squareup.okhttp.RequestBody;
    import com.squareup.okhttp.internal.Util;
    
    import java.io.File;
    import java.io.IOException;
    
    import okio.BufferedSink;
    import okio.Okio;
    import okio.Source;
    
    public class ProgressRequestBody extends RequestBody {
    
    
    private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE
    
    private final File file;
    private final ProgressListener listener;
    private final String contentType;
    
    public ProgressRequestBody(File file, String contentType, ProgressListener listener) {
        this.file = file;
        this.contentType = contentType;
        this.listener = listener;
    }
    
    
    @Override
    public long contentLength() {
        return file.length();
    }
    
    @Override
    public MediaType contentType() {
        return MediaType.parse(contentType);
    }
    
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(file);
            long total = 0;
            long read;
    
            while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                total += read;
                sink.flush();
    
                this.listener.transferred(total);
    
            }
        } finally {
            Util.closeQuietly(source);
        }
    }
    
    public interface ProgressListener {
        void transferred(long num);
    }
    
    }  
    

    you can copy this class as is

    Now in your activity or fragment implement the ProgressListener from the ProgressRequestBody class and call a following methods

       public void uploadWithProgrss(File file) {
    
    
        RequestBody requestBody = new MultipartBuilder()
    
                //build multipart request
                .type(MultipartBuilder.FORM)
    
                //name= KEY for your param
                //filename = VALUE of the param - in our case filename
                //attach the custom ProgressRequestBody in form of (File file, String type, Interface ProgressRequestBody.ProgressListener)
                //Set type depending on your content type if video set it to "video/mp4" or "image/jpeg" if image
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"digital_product[attachment]\"; filename=\"" + file.getName() + "\""),
                        new ProgressRequestBody(file, type2, this))
    
                //attach the rest of Request body parameters if any
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"digital_product[price]\""),
                        RequestBody.create(MediaType.parse("text/plain"), etPrice.getText().toString()))
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"digital_product[title]\""),
                        RequestBody.create(MediaType.parse("text/plain"), etCaption.getText().toString()))
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"digital_product[description]\""),
                        RequestBody.create(MediaType.parse("text/plain"), etCaption.getText().toString()))
                .build();
    
    
        //Build your request
        Request request = new Request.Builder()
                //your url
                .url(BuildConfig.API_URL + "api/v1/users/me/digital_products")
                //request header if any
                .addHeader("Authorization", "Bearer " + app.getAccessToken())
                //type of the request, i this case post request with request body
                .post(requestBody)
                .build();
    
        client.setReadTimeout(1, TimeUnit.MINUTES);
        client.setConnectTimeout(1, TimeUnit.MINUTES);
        client.setWriteTimeout(1, TimeUnit.MINUTES);
    
        final Call call = client.newCall(request);
    
        call.enqueue(new com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
    
            }
    
            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                if (response.isSuccessful()) {
                    //Handle success
                } else {
                    call.cancel();
                    //handle error
                }
            }
        });
    }
    
    @Override
    public void transferred(final long num) {
        //progress bar had to be updated from the UI thread
        new Handler(activity.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                //just chacking if fragment is added
                if (isAdded()) {
                    //Updating progress bar
                    progressBar.setProgress((int) ((num / (float) file.length()) * 100));
                }
            }
        });
    }
    

提交回复
热议问题