使用Retrofit2.0同时向服务器上传文字和图片(一张)

首先定义一个接口。

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) {

            }
        });

猜你喜欢

转载自blog.csdn.net/qq_38256015/article/details/80548670
今日推荐