使用 Retrofit 在 Android 中进行多文件上传并显示上传进度。

huangapple 未分类评论44阅读模式
英文:

Retrofit multiple file upload with progress in android

问题

public void Loader() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);
}

ArrayList<files> listUrl = new ArrayList<>();

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SELECT_PICTURES) {
        if (resultCode == MainActivity.RESULT_OK) {
            if (data.getClipData() != null) {
                int count = data.getClipData().getItemCount();
                if (count > 5) {
                    count = 4;
                }
                image.setVisibility(GONE);
                slider.setVisibility(VISIBLE);
                int currentItem = 0;
                while (currentItem < count) {
                    test.get(currentItem).setVisibility(VISIBLE);
                    Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                    getImageFilePath(imageUri);
                    currentItem = currentItem + 1;
                }
            }
            if (files.size() > 0) {
                uploadFiles();
            }
        }
    }
}

public void getImageFilePath(Uri uri) {
    File file = new File(uri.getPath());
    String[] filePath = file.getPath().split(":");
    String image_id = filePath[filePath.length - 1];
    Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
    if (cursor != null) {
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        files.add(imagePath);
        cursor.close();
    }
}

public void uploadFiles() {
    File[] filesToUpload = new File[files.size()];
    for (int i = 0; i < files.size(); i++) {
        filesToUpload[i] = new File(files.get(i));
    }
    showProgress("正在上传媒体文件...");
    FileUploader fileUploader = new FileUploader();
    fileUploader.uploadFiles("/", "file", filesToUpload, new FileUploader.FileUploaderCallback() {
        @Override
        public void onError() {
            hideProgress();
        }

        @Override
        public void onFinish(String[] responses) {
            hideProgress();
            for (int i = 0; i < responses.length; i++) {
                String str = responses[i];
                Log.e("响应 " + i, responses[i]);
            }
        }

        @Override
        public void onProgressUpdate(int currentpercent, int totalpercent, int filenumber) {
            updateProgress(totalpercent, "正在上传文件 " + filenumber, "");
            Log.e("进度状态", currentpercent + " " + totalpercent + " " + filenumber);
        }
    });
}

public void updateProgress(int val, String title, String msg) {
    pDialog.setTitle(title);
    pDialog.setMessage(msg);
    pDialog.setProgress(val);
}

public void showProgress(String str) {
    try {
        pDialog.setCancelable(false);
        pDialog.setTitle("请稍候");
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setMax(100); // 进度对话框最大值
        pDialog.setMessage(str);
        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog.show();
    } catch (Exception e) {
    }
}

public void hideProgress() {
    try {
        if (pDialog.isShowing())
            pDialog.dismiss();
    } catch (Exception e) {
    }
}
英文:

I use the library Retrofit2 to upload multiple images to the server, the code below.
I don’t understand why only 1 photo is uploaded.On the server receiver, too, only one photo.
Please tell me what is wrong with my code and how can I solve this?
The code was taken from the github from the multiboot lesson. At the first start, 4 photos were uploaded, as I chose.
And for some reason, if I select 1 photo, nothing happens.

public void Loader(){
            Intent intent = new Intent();
            intent.setType(&quot;image/*&quot;);
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,&quot;Select Picture&quot;), 1);
    }
    ArrayList&lt;files&gt; listUrl = new ArrayList&lt;&gt;();
    /**Обработчик фото*/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == SELECT_PICTURES) {
            if (resultCode == MainActivity.RESULT_OK) {
                if (data.getClipData() != null) {
                    int count = data.getClipData().getItemCount();
                    if(count&gt;5){
                        count = 4;
                    }
                    image.setVisibility(GONE);
                    slider.setVisibility(VISIBLE);
                    int currentItem = 0;
                    while (currentItem &lt; count) {
                        test.get(currentItem).setVisibility(VISIBLE);
                        Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                        getImageFilePath(imageUri);
                        currentItem = currentItem + 1;
                    }
                }if(files.size()&gt;0){
                    uploadFiles();
                }

            }
        }
    }
    public void getImageFilePath(Uri uri) {

        File file = new File(uri.getPath());
        String[] filePath = file.getPath().split(&quot;:&quot;);
        String image_id = filePath[filePath.length - 1];
        Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + &quot; = ? &quot;, new String[]{image_id}, null);
        if (cursor!=null) {
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            files.add(imagePath);
            cursor.close();
        }
    }

    public void uploadFiles(){
        File[] filesToUpload = new File[files.size()];
        for(int i=0; i&lt; files.size(); i++){
            filesToUpload[i] = new File(files.get(i));
        }
        showProgress(&quot;Uploading media ...&quot;);
        FileUploader fileUploader = new FileUploader();
        fileUploader.uploadFiles(&quot;/&quot;, &quot;file&quot;, filesToUpload, new FileUploader.FileUploaderCallback() {
            @Override
            public void onError() {
                hideProgress();
            }

            @Override
            public void onFinish(String[] responses) {
                hideProgress();
                for(int i=0; i&lt; responses.length; i++){
                    String str = responses[i];
                    Log.e(&quot;RESPONSE &quot;+i, responses[i]);
                }
            }

            @Override
            public void onProgressUpdate(int currentpercent, int totalpercent, int filenumber) {
                updateProgress(totalpercent,&quot;Uploading file &quot;+filenumber,&quot;&quot;);
                Log.e(&quot;Progress Status&quot;, currentpercent+&quot; &quot;+totalpercent+&quot; &quot;+filenumber);
            }
        });
    }

    public void updateProgress(int val, String title, String msg){
        pDialog.setTitle(title);
        pDialog.setMessage(msg);
        pDialog.setProgress(val);
    }

    public void showProgress(String str){
        try{
            pDialog.setCancelable(false);
            pDialog.setTitle(&quot;Please wait&quot;);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setMax(100); // Progress Dialog Max Value
            pDialog.setMessage(str);
            if (pDialog.isShowing())
                pDialog.dismiss();
            pDialog.show();
        }catch (Exception e){

        }
    }

    public void hideProgress() {
        try {
            if (pDialog.isShowing())
                pDialog.dismiss();
        } catch (Exception e) {

        }
    }

huangapple
  • 本文由 发表于 2020年4月10日 03:42:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/61129019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定