日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

2020-12-04使用retrofit上传下载文件,监听下载进度

發(fā)布時間:2023/12/3 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 2020-12-04使用retrofit上传下载文件,监听下载进度 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

retrofit2上傳、下載文件

一、上傳文件

1、使用表單上傳文件;結(jié)合Rxjava

先定義ApiService接口

@Multipart //Multipart表單 @POST("{url}") //post上傳地址 Observable<ResponseBody> uploadFiles(@Path(value = "url",encoded = true) String url,@PartMap() Map<String, RequestBody> maps); //請求body的map集合

組建請求體

//參數(shù)map Map<String,RequestBody> paraMap = new HashMap<>(); //隨文件一起上傳的表單其他參數(shù),備注,用戶id等 paraMap.put("remark3",RequestBody.create(MediaType.parse("text/plain"), "備注")); paraMap.put("userId", RequestBody.create(MediaType.parse("text/plain"), userId)); //文件1 File file = new File(filePath); if(file.exists()) {//表單格式封裝文件RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);//固定寫法;其中"file1"是取文件名的key值,"filename"為固定寫法,后面是原文件名;服務端獲取到的文件為例如:file1=abc.txtparaMap.put("file1\"; filename=\"" + file.getName(), requestFile); } //再放一個文件 File file2 = new File(filePath); if(file2.exists()) {//表單格式封裝文件RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file2);//服務端獲取到的文件為例如:file2=abc.txtparaMap.put("file2\"; filename=\"" + file2.getName(), requestFile); }

開始上傳

ApiService apiService = RxRetrofitClient.getApiService(); //method是后臺接口方法名如"uploadImages",當前你已經(jīng)封裝了retrofit2的baseUrl Observable<ResponseBody> uploadFileObervable = apiService.uploadFiles(method, images);

二、文件下載

定義retrofit2下載接口

/*** 下載文件,支持大文件下載* @param url 地址* @return 觀察者*/ @Streaming //使用流媒體 @GET Observable<ResponseBody> downLoadFile(@NonNull @Url() String url);

文件下載方法

/*** 下載方法** @param url 地址* @param destDir 存儲文件夾* @param fileName 文件名稱* @param fileDownLoadObserver 回調(diào)*/ public void downloadFile(String url, final String destDir, final String fileName, final FileDownLoadObserver<File> fileDownLoadObserver) {Disposable subscribe = RxRetrofitClient.getApiService().downLoadFile(url).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).observeOn(Schedulers.computation()).map(new Function<ResponseBody, File>() {@Overridepublic File apply(ResponseBody responseBody) throws Exception {return fileDownLoadObserver.saveFile(responseBody, destDir, fileName);}}).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {@Overridepublic void accept(File file) throws Exception {fileDownLoadObserver.onDownLoadSuccess(file);}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable throwable) throws Exception {fileDownLoadObserver.onDownLoadFail(throwable);}}, new Action() {@Overridepublic void run() throws Exception {fileDownLoadObserver.onComplete();}});//管理請求生命周期addSubscribe(subscribe); }

文件下載監(jiān)聽;

public abstract class FileDownLoadObserver<T> {//可以重寫,具體可由子類實現(xiàn)public void onComplete() {}//下載成功的回調(diào)public abstract void onDownLoadSuccess(T t);//下載失敗回調(diào)public abstract void onDownLoadFail(Throwable throwable);//下載進度監(jiān)聽public abstract void onProgress(int progress,long total);/*** 將文件寫入本地* @param responseBody 請求結(jié)果全體* @param destFileDir 目標文件夾* @param destFileName 目標文件名* @return 寫入完成的文件* @throws IOException IO異常*/public File saveFile(ResponseBody responseBody, String destFileDir, String destFileName) throws IOException {InputStream is = null;byte[] buf = new byte[2048];int len = 0;FileOutputStream fos = null;try {is = responseBody.byteStream();final long total = responseBody.contentLength();long sum = 0;File dir = new File(destFileDir);if (!dir.exists()) {dir.mkdirs();}File file = new File(dir, destFileName);fos = new FileOutputStream(file);while ((len = is.read(buf)) != -1) {sum += len;fos.write(buf, 0, len);final long finalSum = sum;onProgress((int) (finalSum * 100 / total),total);}fos.flush();return file;} finally {try {if (is != null) is.close();} catch (IOException e) {e.printStackTrace();}try {if (fos != null) fos.close();} catch (IOException e) {e.printStackTrace();}}}}

?

總結(jié)

以上是生活随笔為你收集整理的2020-12-04使用retrofit上传下载文件,监听下载进度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。