Retrofit上传文件到oss文件存储

发布时间:2023年12月17日
@Override
public Observable<BaseResp<UploadFileInfoResp>> getUploadFileUrl(UploadFileInfoReq uploadFileInfoReq) {
    return apiService.getUploadFileUrl(uploadFileInfoReq);
}
@Override
public Observable<ResponseBody> uploadFileDirect(String url, Map<String, String> headers, RequestBody requestBody) {
    return apiService.uploadFileDirect(url, headers, requestBody);
}
public class UploadFileInfoReq {
    public String fileName;
    public long fileSize;
    public boolean randomFileName;
    public String systemCode;
}
public class UploadFileInfoResp {
    public long fileId;
    public String fileUrl;
    public String uploadUrl;
    public Map<String, String> headers;
}

public void getUploadFileUrl(File file, UploadFileInfoReq uploadFileInfoReq) {
    dataRepository.getUploadFileUrl(uploadFileInfoReq)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(this)
            .subscribe(new DisposableObserver<BaseResp<UploadFileInfoResp>>() {
                @Override
                public void onNext(@NonNull BaseResp<UploadFileInfoResp> response) {
                    if (response.code == BaseConstants.API_HANDLE_SUCCESS) {
                        uploadFileDirect(file, response.data);
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
public void uploadFileDirect(File file, UploadFileInfoResp uploadFileInfoResp) {

    RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/png"));

    dataRepository.uploadFileDirect(uploadFileInfoResp.uploadUrl, uploadFileInfoResp.headers, requestBody)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(this)
            .subscribe(new DisposableObserver<ResponseBody>() {
                @Override
                public void onNext(@NonNull ResponseBody response) {
                    Log.i("xxx", "------ done-");
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

}

topBarView.setOnSettingsClickListener(new TopBarView.OnSettingsItemClickListener() {
    @Override
    public void onClick(View view) {
        File file = new File(getExternalCacheDir().getAbsolutePath() + "/xxx.png");
        showToast("size=" + file.length());
        UploadFileInfoReq uploadFileInfoReq = new UploadFileInfoReq("TestFile", file.length(), "Test_File_001");
        viewModel.getUploadFileUrl(file, uploadFileInfoReq);
    }
});
文章来源:https://blog.csdn.net/hejinyin/article/details/135001456
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。