Rxjava上传多张图片(腾讯云)

Rxjava上传多张图片(腾讯云)

直接上代码吧
1.Rxjava上传控制器

public class HnUploadListImageControl {
    /**
     * 回调接口
     */
    public interface UploadCallback {

        /**
         * 上传完成
         */
        void onSuccess(List picUrls);

        /**
         * 上传失败
         */
        void onError(String msg);
    }

    /**
     * @param images        图片地址
     * @param callback 回调接口
     */
    @SuppressLint("CheckResult")
    public static void putImgs(final List images, final UploadCallback callback) {
     
        final ArrayList resultImagePath = new ArrayList<>();
        try {
            Observable
                    // 依次发送list中的数据
                    .fromIterable(images)
                    // 变换,在这里上传图片
                    // 修改为concatMap确保图片顺序
                    .concatMap(new Function>() {
                        @Override
                        public ObservableSource apply(final String s) throws Exception {
                            return Observable.create(new ObservableOnSubscribe() {
                                @Override
                                public void subscribe(final ObservableEmitter emitter) throws Exception {
                                    HnUpLoadPhotoControl.getTenSign(s, HnUpLoadPhotoControl.UploadImage, new HnUpLoadPhotoControl.UpStutaListener() {
                                        @Override
                                        public void uploadSuccess(String key, Object token, int type) {
                                            emitter.onNext(key);
                                            emitter.onComplete();
                                        }

                                        @Override
                                        public void uploadProgress(int progress) {

                                        }

                                        @Override
                                        public void uploadError(int code, String msg) {
                                            emitter.onError(new Exception(msg));
                                        }
                                    });
                                }
                            }).subscribeOn(Schedulers.io());
                        }
                    })
                    // 线程切换
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer() {
                        @Override
                        public void accept(String o) throws Exception {
                            resultImagePath.add(o);
                            // 如果全部完成,调用成功接口
                            if (resultImagePath.size() == images.size()) {
                                callback.onSuccess(resultImagePath);
                            }
                        }
                    });

        } catch (Exception e) {
            callback.onError(e.getMessage());
        }


    }

}

2.腾讯云上传方法(当然了 这里面的一些配置参数就没有改了)

public class HnUpLoadPhotoControl {
    private static CosXmlService cosXmlService;
    public static COSXMLUploadTask cosxmlUploadTask;
    public static final int UploadImage = 1;
    public static final int UploadVideo = 2;

    /**
     * 初始化腾讯上传
     */
    public static void initTenceUpload() {
        //创建COSClientConfig对象,根据需要修改默认的配置参数
        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                .setAppidAndRegion(HnAppConfigUtil.getTencentConfig(NetConstant.TENCENT_APPID), NetConstant.TENCENT_REGION)
                .setDebuggable(true)
                .builder();

        if (HnAppConfigUtil.getTencentConfig() == null || HnAppConfigUtil.getTencentConfig().getCredentials() == null || TextUtils.isEmpty(HnAppConfigUtil.getTencentConfig().getCredentials().getSessionToken())) {
            cosXmlService = new CosXmlService(HnBaseApplication.getContext(), serviceConfig,
                    (QCloudCredentialProvider) new LocalCredentialProvider(NetConstant.TENCENT_SECREID,
                            NetConstant.TENCENT_SECRETKEY, 300));
        } else {
            QCloudCredentialProvider credentialProvider = new MyCredentialProvider();
            cosXmlService = new CosXmlService(HnBaseApplication.getContext(), serviceConfig, credentialProvider);
        }


    }

    /**
     * 腾讯上传签名
     */
    public static void getTenSign(final String path, final int type, UpStutaListener listener) {
        mListener = null;
        mListener = listener;
        if (!checkConnectionOk(HnBaseApplication.getContext())) {
            if (mListener != null) {
                mListener.uploadError(1, "连接失败,请检查网络是否正常");
            }
            return;
        }
        if (TextUtils.isEmpty(path)) {
            if (mListener != null) {
                mListener.uploadError(1, "上传失败,地址错误");
            }
            return;
        }
        upload(path, type);
    }

    /**
     * 腾讯上传签名
     */
    public static void getTenSign(final String path, final int type) {
        if (!checkConnectionOk(HnBaseApplication.getContext())) {
            if (mListener != null) {
                mListener.uploadError(1, "连接失败,请检查网络是否正常");
            }
            return;
        }
        if (TextUtils.isEmpty(path)) {
            if (mListener != null) {
                mListener.uploadError(1, "上传失败,地址错误");
            }
            return;
        }
        upload(path, type);
    }


    private static void upload(final String path, final int type) {
        if (cosXmlService == null) {
            initTenceUpload();
        }
        String cosPath = null;
        if (UploadImage == type)
            cosPath = "/image/" + HnDateUtils.today() + "/" + System.currentTimeMillis() + "." + path.substring(path.lastIndexOf(".") + 1);
        else if (UploadVideo == type)
            cosPath = "/video/" + HnDateUtils.today() + "/" + System.currentTimeMillis() + "." + path.substring(path.lastIndexOf(".") + 1);

        TransferConfig transferConfig = new TransferConfig.Builder().build();
        TransferManager transferManager = new TransferManager(cosXmlService, transferConfig);
        final String finalCosPath = cosPath;
        cosxmlUploadTask = transferManager.upload(HnAppConfigUtil.getTencentConfig(NetConstant.TENCENT_BUCKET), cosPath, path, null);
        cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long complete, long target) {
                final float progress = 1.0f * complete / target * 100;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (mListener != null) {
                            mListener.uploadProgress((int) progress);
                        }
                    }
                });
            }
        });

        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, final CosXmlResult result) {
                if (result != null) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {

                            if (mListener != null) {
                                if (UploadVideo == type) {
                                    if (!result.accessUrl.toLowerCase().startsWith("http")) {
                                        mListener.uploadSuccess("http://" + result.accessUrl, null, type);
                                    } else {
                                        mListener.uploadSuccess(result.accessUrl, null, type);
                                    }
                                } else {
                                    String s = "";
                                    if (path.toLowerCase().endsWith("gif")) {
                                        s = NetConstant.IMAGE_CDN_GIF_PATH + finalCosPath;
                                    } else if (path.toLowerCase().endsWith("png") || path.toLowerCase().endsWith("jpg")) {
                                        s = HnAppConfigUtil.getTencentConfig(NetConstant.IMAGE_CDN_PATH) + finalCosPath;
                                    } else {
                                        if (!result.accessUrl.toLowerCase().startsWith("http")) {
                                            s = "http://" + result.accessUrl;
                                        } else {
                                            s = result.accessUrl;
                                        }
                                    }
                                    mListener.uploadSuccess(s, null, type);
                                }

                            }
                        }
                    });
                }
            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                HnLogUtils.e("Failed: " + (exception == null ? serviceException.getMessage() : exception.toString()));
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (mListener != null) {
                            mListener.uploadError(1, "上传失败,请稍后重试");
                        }
                    }
                });
            }
        });
    }


    private static UpStutaListener mListener;

    public static void setUpStutaListener(UpStutaListener listener) {
        mListener = listener;
    }

    public static void removeUpListener() {
        if (cosxmlUploadTask != null) cosxmlUploadTask.cancel();
        mListener = null;
    }

    public interface UpStutaListener {
        void uploadSuccess(String key, Object token, int type);

        void uploadProgress(int progress);

        void uploadError(int code, String msg);
    }
}

3.调用方法

   HnUploadListImageControl.putImgs(mUrlData, new HnUploadListImageControl.UploadCallback() {
                @Override
                public void onSuccess(List picUrls) {
                    if (isFinishing() || mCommunityBiz == null) return;
                    if (picUrls == null || picUrls.size() < 1) {
                        loadDialogDone();
                        HnAlerterUtils.showAlertTextOnly(HnCommunityPublishActivity.this, "上传失败,请重试");
                        return;
                    }
                    mCommunityBiz.setCommunityPublish(mEtContent.getText().toString().trim(), "image",
                            TextUtils.join(",", picUrls), null, mTvArea.getText().toString());
                }

                @Override
                public void onError(String msg) {
                    if (isFinishing()) return;
                    loadDialogDone();
                    HnAlerterUtils.showAlertTextOnly(HnCommunityPublishActivity.this, "上传失败:" + msg);
                }
            });

你可能感兴趣的:(Rxjava上传多张图片(腾讯云))