0

I visit the below links but it upload one image per request.

I want to upload multiple images per request with retrofit2 with progress.

Is it possible to show progress bar when uploading the image via Retrofit 2?

retrofit-multiple-file-upload-with-progress

Fateme
  • 11
  • 5
  • please add your code and your effort for solving the problem. your question is not defined clearly. – nima Feb 02 '20 at 08:36
  • @novonimo please see this link. this is sample code i want to change it to MultipartBody.Part[] https://stackoverflow.com/a/33384551/12579800 – Fateme Feb 02 '20 at 08:50

1 Answers1

0

yes it is, use this code

first add this class to your project:

public class ProgressRequestBody extends RequestBody{
    private static final int DEFAULT_BUFFER_SIZE=2048;
    private File file;
    private UploadCallbacks listener;
    private String content_type;
    public ProgressRequestBody(final File file,String content_type,final UploadCallbacks listener){
        this.content_type=content_type;
        this.file=file;
        this.listener=listener;
    }
    @Override public long contentLength(){
        return file.length();
    }
    @Override public MediaType contentType(){
        return MediaType.parse(content_type+"/*");
    }
    @Override public void writeTo(BufferedSink sink) throws IOException{
        long fileLength=file.length();
        byte[] buffer=new byte[DEFAULT_BUFFER_SIZE];
        try(FileInputStream in=new FileInputStream(file)){
            long uploaded=0;
            int read;
            Handler handler=new Handler(Looper.getMainLooper());
            while((read=in.read(buffer))!=-1){
                handler.post(new ProgressUpdater(uploaded,fileLength));
                uploaded+=read;
                sink.write(buffer,0,read);
            }
        }
    }
    public interface UploadCallbacks{
        void onProgressUpdate(int percentage);
    }
    private class ProgressUpdater implements Runnable{
        private long uploaded;
        private long total;
        public ProgressUpdater(long uploaded,long total){
            this.uploaded=uploaded;
            this.total=total;
        }
        @Override public void run(){
            listener.onProgressUpdate((int)(100*uploaded/total));
        }
    }
}

then implement ProgressRequestBody.UploadCallbacks in the activity or fragment you want to show the progress.

class EditUserProfile4Fragment : BaseFragment(), ProgressRequestBody.UploadCallbacks {


    override fun onProgressUpdate(percentage: Int) {

    }
}

now, for making the multipartBody, you need to use this code

send(MultipartBody.Part.createFormData("IMAGE_NAME", "IMAGE_NAME", ProgressRequestBody(IMAGE_FILE, "CONTENT-TYPE", this@EditUserProfile4Fragment))
SinaMN75
  • 6,742
  • 5
  • 28
  • 56
  • thanks for answer. I saw your sample code.but i want to upload multiple images per request. – Fateme Feb 02 '20 at 13:58