1、单张图片上传
private void setHttpPortrait(final String name, final String strPath) {//name:参数名称;strPath:图片路径
File file = new File(strPath);
RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData(name, file.getName(), imageBody);
Call<PictureBean> repos = HttpUtils.setRetrofit().setHttpPortrait(imageBodyPart);
repos.enqueue(new Callback<PictureBean>() {
@Override
public void onResponse(Call<PictureBean> call, Response<PictureBean> response) {
try {
if (response.body().isOk()) {//请求成功
//返回数据处理
} else {
//图片上传失败
}
} catch (Exception e) {
//返回数据异常
}
}
@Override
public void onFailure(Call<PictureBean> call, Throwable t) {
//请求异常
}
});
}
@Multipart
@POST("home/upload-image")
Call<PictureBean> setHttpPortrait(@Part MultipartBody.Part part);
2、带参数图片上传
private void setHttpPortrait(final String name, final String strPath) {
File file = new File(strPath);
RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData(name, file.getName(), imageBody);
MultipartBody.Part txtBodyPart = MultipartBody.Part.createFormData("id", "参数id");
Call<PictureBean> repos = HttpUtils.setRetrofit().setHttpPortrait(txtBodyPart, imageBodyPart);
repos.enqueue(new Callback<PictureBean>() {
@Override
public void onResponse(Call<PictureBean> call, Response<PictureBean> response) {
try {
if (response.body().isOk()) {//请求成功
//返回数据处理
} else {
//图片上传失败
}
} catch (Exception e) {
//返回数据异常
}
}
@Override
public void onFailure(Call<PictureBean> call, Throwable t) {
//请求异常
}
});
}
@Multipart
@POST("home/upload-image")
Call<PictureBean> setHttpPortrait(@Part MultipartBody.Part id, @Part MultipartBody.Part part);
3、多张图片上传
private void setHttpPortrait(final String name, final List<String> paths) {
showLoading();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (String path : paths) {
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file);
builder.addFormDataPart("files", file.getName(), requestBody);
}
List parts = builder.build().parts();
Call<PictureBean> repos = HttpUtils.setRetrofit().setHttpDataPortrait(parts);
repos.enqueue(new Callback<PictureBean>() {
@Override
public void onResponse(Call<PictureBean> call, Response<PictureBean> response) {
try {
if (response.body().isOk()) {
//返回数据处理
} else {
//图片上传失败
}
} catch (Exception e) {
//返回数据异常
}
}
@Override
public void onFailure(Call<PictureBean> call, Throwable t) {
//请求异常
}
});
}
@Multipart
@POST("home/upload-image")//多张上传图片
Call<PictureBean> setHttpDataPortrait(@Part List file);