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.txt
paraMap.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.txt
paraMap.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>() {
@Override
public File apply(ResponseBody responseBody) throws Exception {
return fileDownLoadObserver.saveFile(responseBody, destDir, fileName);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
@Override
public void accept(File file) throws Exception {
fileDownLoadObserver.onDownLoadSuccess(file);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
fileDownLoadObserver.onDownLoadFail(throwable);
}
}, new Action() {
@Override
public 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();
}
}
}
}