網(wǎng)上找了很多文章,看的有點(diǎn)眼花繚亂除秀,這里只講下可行方案,順便做下筆記算利;
本人用的rxjava和Retrofit册踩。下面是個(gè)上傳txt格式的錯(cuò)誤日志的例子
- 1.首先是定義下接口(由于自己的接口路徑跟默認(rèn)配置不一樣,所以用了@Url)
//上傳錯(cuò)誤日志
@Multipart
@POST()
Observable<ErrorLogEntity> addErrorLog(@Url String baseurl,@PartMap
Map<String, RequestBody> params, @Part MultipartBody.Part file);
- 2.實(shí)現(xiàn)方法
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實(shí)例
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part借助文件名完成最終的上傳
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
return null;
}
- 6參數(shù)都有了效拭,只要調(diào)用addErrorLog方法就好了(謝謝大家觀看T菁)