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

首先定义一个接口。

public interface PostInterface {
    @POST("addPost")
    @Multipart
//    Call> testFileUpload(@Part("content") String content,@Part() RequestBody requestBody);
//    Call testFileUpload(@Part("content") String content, @PartMap Map params);
//    Call> testFileUpload(@Body RequestBody requestBody);
   // Call updateAvatar (@Part("content") String content,@Part("uploadFile\"; filename=\"test.jpg\"") RequestBody imgs);
    Call 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 call =     postInterface.updateAvatar(content.getText().toString(),requestBody);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.e("aaa","success");
            }

            @Override
            public void onFailure(Call call, Throwable t) {

            }
        });

你可能感兴趣的:(使用Retrofit2.0同时向服务器上传文字和图片(一张))