最近手頭事比較多,抽個空把以前系列也補充一下。今天要說的是文件上傳php
首先ApiServer
,要使用Multipart
註解java
//上傳圖片(私有接口)
@POST("index.php/PrivateApi/Goods/uploadPic")
@Multipart
Observable<BaseListModel<String>> upLoadImg(@Part MultipartBody.Part parts);
複製代碼
而後是Presenter
api
public void upLoadImg(String path) {
File file = new File(path);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("headimg", file.getName(), requestFile);
addDisposable(apiServer.upLoadImg(filePart), new BaseObserver<BaseListModel<String>>(baseView, true) {
@Override
public void onSuccess(BaseListModel<String> o) {
baseView.onUpLoadSucc(o.getData());
}
@Override
public void onError(String msg) {
baseView.showError(msg);
}
});
}
複製代碼
成功後作個提示就好架構
ApiServer
app
@POST("index.php/PrivateApi/Goods/uploadPic")
@Multipart
Observable<BaseListModel<String>> upLoadImg(@Part MultipartBody.Part[] parts);
複製代碼
Presenter
ide
public void upLoadImg(ArrayList<String> media) {
if (media == null) {
return;
}
MultipartBody.Part[] parts = new MultipartBody.Part[media.size()];
int cnt = 0;
for (String m : media) {
File file = new File(m);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("headimg[]", file.getName(), requestFile);
parts[cnt] = filePart;
cnt++;
}
addDisposable(apiServer.upLoadImg(parts), new BaseObserver<BaseListModel<String>>(baseView, true) {
@Override
public void onSuccess(BaseListModel<String> o) {
baseView.onUpLoadSucc(o.getData());
}
@Override
public void onError(String msg) {
baseView.showError(msg);
}
});
}
複製代碼
ApiServer
post
//上傳圖片(私有接口)
@POST("index.php/PrivateApi/Goods/uploadPic")
@Multipart
Observable<BaseListModel<String>> upLoadImg(@Part MultipartBody.Part[] parts, @Part("APP_KEY") RequestBody APP_KEY, @Part("APP_TOKEN") RequestBody APP_TOKEN);
複製代碼
Presenter
spa
public void upLoadImg(ArrayList<String> media) {
if (media == null) {
return;
}
MultipartBody.Part[] parts = new MultipartBody.Part[media.size()];
int cnt = 0;
for (String m : media) {
File file = new File(m);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("headimg[]", file.getName(), requestFile);
parts[cnt] = filePart;
cnt++;
}
RequestBody appkey = RequestBody.create(MediaType.parse("multipart/form-data"), AppConstant.APP_KEY);
RequestBody apptoken = RequestBody.create(MediaType.parse("multipart/form-data"), UserImpl.getAppToken());
//
addDisposable(apiServer.upLoadImg(parts, appkey, apptoken), new BaseObserver<BaseListModel<String>>(baseView, true) {
@Override
public void onSuccess(BaseListModel<String> o) {
baseView.onUpLoadSucc(o.getData());
}
@Override
public void onError(String msg) {
baseView.showError(msg);
}
});
}
複製代碼
至此,使用Retrofit
文件上傳暫時告一段落。code