首先定义一个接口。
public interface PostInterface {
@POST("addPost")
@Multipart
// Call<MediaBrowserServiceCompat.Result<String>> testFileUpload(@Part("content") String content,@Part() RequestBody requestBody);
// Call<ResponseBody> testFileUpload(@Part("content") String content, @PartMap Map<String,RequestBody> params);
// Call<MediaBrowserServiceCompat.Result<String>> testFileUpload(@Body RequestBody requestBody);
// Call<ResponseBody> updateAvatar (@Part("content") String content,@Part("uploadFile\"; filename=\"test.jpg\"") RequestBody imgs);
Call<ResponseBody> updateAvatar (@Part("content") String content,@Part("file\"; filename=\"image.png") RequestBody imgs);
}
获取本地相册的图片
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
imagePath = c.getString(columnIndex);
showImage(imagePath);
c.close();
向后端发送图片
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://119.29.233.28:9090/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
// application/octet-stream multipart/form-data
PostInterface postInterface = retrofit.create(PostInterface.class);
Call<ResponseBody> call = postInterface.updateAvatar(content.getText().toString(),requestBody);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("aaa","success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});