网上找了很多文章,看的有点眼花缭乱,这里只讲下可行方案,顺便做下笔记;
本人用的rxjava和Retrofit。下面是个上传txt格式的错误日志的例子
- 1.首先是定义下接口(由于自己的接口路径跟默认配置不一样,所以用了@Url)
//上传错误日志
@Multipart
@POST()
Observable<ErrorLogEntity> addErrorLog(@Url String baseurl,@PartMap
Map<String, RequestBody> params, @Part MultipartBody.Part file);
- 2.实现方法
public Disposable addErrorLog(String url, Map<String, RequestBody> stringRequestBodyMap, MultipartBody.Part file,DisposableObserver<ErrorLogEntity> consumer){
return getService(ApiService.class).addErrorLog(url,stringRequestBodyMap,file).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(consumer);
- 3.生成Map<String, RequestBody>
Map<String, RequestBody> stringRequestBodyMap = new HashMap<>();
FileUtils.putRequestBodyMap(stringRequestBodyMap, "name", "张三");
FileUtils.putRequestBodyMap(stringRequestBodyMap, "age", "16");
FileUtils.putRequestBodyMap(stringRequestBodyMap, "fileName", "error.txt");
- 4.生成MultipartBody.Part
MultipartBody.Part file=FileUtils.prepareFilePart("file",fileuri);
- 5.File的工具类FileUtils.java
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
public static void putRequestBodyMap(Map map, String key, String value) {
putRequestBodyMap(map, key, createPartFromString(value));
}
@NonNull
public static RequestBody createPartFromString(String descriptionString) {
if (descriptionString == null) {
descriptionString = "";
}
return RequestBody.create(
MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
}
public static void putRequestBodyMap(Map map, String key, RequestBody body) {
if (!TextUtils.isEmpty(key) && body != null) {
map.put(key, body);
}
}
public static MultipartBody.Part prepareFilePart(String partName, String fileUri) {
File file = new File(fileUri);
if (file != null) {
// 为file建立RequestBody实例
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part借助文件名完成最终的上传
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
return null;
}
- 6参数都有了,只要调用addErrorLog方法就好了(谢谢大家观看!)
网友评论