2020-12-04使用retrofit上传下载文件,监听下载进度
生活随笔
收集整理的這篇文章主要介紹了
2020-12-04使用retrofit上传下载文件,监听下载进度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
retrofit2上傳、下載文件
一、上傳文件
1、使用表單上傳文件;結合Rxjava
先定義ApiService接口
@Multipart //Multipart表單 @POST("{url}") //post上傳地址 Observable<ResponseBody> uploadFiles(@Path(value = "url",encoded = true) String url,@PartMap() Map<String, RequestBody> maps); //請求body的map集合組建請求體
//參數map Map<String,RequestBody> paraMap = new HashMap<>(); //隨文件一起上傳的表單其他參數,備注,用戶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",當前你已經封裝了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 回調*/ 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); }文件下載監聽;
public abstract class FileDownLoadObserver<T> {//可以重寫,具體可由子類實現public void onComplete() {}//下載成功的回調public abstract void onDownLoadSuccess(T t);//下載失敗回調public abstract void onDownLoadFail(Throwable throwable);//下載進度監聽public abstract void onProgress(int progress,long total);/*** 將文件寫入本地* @param responseBody 請求結果全體* @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();}}}}?
總結
以上是生活随笔為你收集整理的2020-12-04使用retrofit上传下载文件,监听下载进度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android自定义控件增加xml标签属
- 下一篇: Windows突然的软件更新