java - Retrofit 2 无法上传图片

标签 java android

我需要使用 Retrofit 2 向 API 发送请求。 我希望请求看起来像 Postman 中的表单数据。

postman 示例 enter image description here

我有一个 ArrayList 和一个要上传的图像。 所以我创建了这个类“CreateGroupCard”

public class  CreateGroupCard implements Serializable
    {

        @SerializedName("userID")
        String userID;
        @SerializedName("group_name")
        String group_name;
        @SerializedName("new_name")
        String new_name;
        @SerializedName("group_id")
        int group_id;
        @SerializedName("group_members")
        List<sendMember> group_members;

        RequestBody photo;

        public CreateGroupCard() {
        }

        private CreateGroupCard(String userID, String group_name, List<sendMember> group_members, RequestBody photo) {
            this.userID = userID;
            this.group_name = group_name;
            this.group_members = group_members;
            this.photo = photo;
        } 
}

这是界面

@POST(createGroupCard)
Call<CreatGroupCardApiResponse> createGroupCard
   (@Header("Authorization") String authorization, @Body CreateGroupCard CreateGroupCard);

这是我的 API 调用

File file = new File(getRealPathFromURI(card.getPhotoUri()));
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("photo",file.getName(),fileReqBody)
                        .build();
CreateGroupCard  groupCard = new CreateGroupCard(user_id,card.getName(),members,requestBody);

ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<CreatGroupCardApiResponse> call = apiInterface.createGroupCard("Bearer " + ACCESS_TOKEN,groupCard);

getRealPathFromURI 方法

public String getRealPathFromURI(Uri contentUri)
    {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

拍照并获取图像

    private void openCamera()
    {


        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, TAKE_PICTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
   {
      super.onActivityResult(requestCode, resultCode, data);

      ImageView imageView = (ImageView) 
          viewPager.findViewWithTag("groupPhoto"+viewPager.getCurrentItem());



      if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
        {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);
            Uri uri = getImageUri(getApplicationContext(), imageBitmap);


            Log.e("URI",uri.toString());
            groupCards.get(viewPager.getCurrentItem()).setPhotoUri(uri);

        }
    }

但是图片没有上传,我做错了什么。

最佳答案

从 postman 那里我可以看到您正在将数据作为表单数据发送,因此您可以这样做:

@POST("<your endurl>")
    Call<CreatGroupCardApiResponse> createGroupCard(@Header("Authorization") String authorization,@PartMap HashMap<String, RequestBody> partmap,@Part MultipartBody.Part part);

创建 RequestBody 类型的 HashMap :

HashMap<String, RequestBody> partBodyMap = new HashMap()

关于java - Retrofit 2 无法上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59623836/

相关文章:

java - 尝试在java中查找数组中字符串的索引

java - Eclipse 与 Netbeans Web 服务工具

java - 更改长变量的格式?

java - 当我们在tomcat服务器中替换为新的PKI时,SSL证书错误

android - 使用 MPAndroidChart 库时 width and height must be > 0 错误

android - 圆形 ListView(半圆上的项目)

java - Mockito - 是否有 "value not in List"的匹配器?

Android SharedPreferences 限制

java - 我希望在 android 期间一遍又一遍地检查它,直到它在 android 上等于

android - 如何使用 POST 为 Parse 服务器上传图像?