Retrofit上传单图、多图、图文
2017-05-18 本文已影响6758人
白日梦__
上传单图
以上传头像为例
@Multipart
@POST(URLConstants.uploadAvatar)
Call<ResponseBody> uploadAvatar(@Part MultipartBody.Part imgs);
private void uploadAvatar(String path) {
File file = new File(path);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
RetrofitUtils.getService().uploadAvatar(part).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
} else {
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
多图和文字参数一起上传
以意见反馈页面为例
@Multipart
@POST(URLConstants.feedBack)
Call<ResponseBody> feedBack(@Part("Content") String Content,@Part("ContactInformation")String conInfo,
@Part() List<MultipartBody.Part> parts);
content --反馈的内容
conInfo--联系方式
具体参数由实际来定
List<MultipartBody.Part> parts
--图片列表
List<MultipartBody.Part> parts = new ArrayList<>();
for (int i = 0; i < selImageList.size(); i++) {
//这里采用的Compressor图片压缩
File file = new Compressor.Builder(FeedBackActivity.this)
.setMaxWidth(720)
.setMaxHeight(1080)
.setQuality(80)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.build()
.compressToFile(new File(selImageList.get(i).path));
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
parts.add(part);
}
RetrofitUtils.getService().feedBack(etFeedBack.getText().toString(),etContact.getText().toString(),parts).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
} else {
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
以下是上传图文的一个坑
@Multipart
@POST(URLConstants.feedBack)
Call<ResponseBody> feedBack(@Part("Content") String Content,@Part("ContactInformation")String conInfo,
@Part() List<MultipartBody.Part> parts);
如上,Content 和 conInfo 以String上传的话,服务端接收到的参数会带双引号
解决办法:用RequestBody上传
@Multipart
@POST(URLConstants.feedBack)
Call<ResponseBody> feedBack(@Part("Content") RequestBody Content,@Part("ContactInformation")RequestBody conInfo,
@Part() List<MultipartBody.Part> parts);
String转RequestBody方法:
public RequestBody toRequestBody(String value) {
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
return requestBody;
}