如何将Base64编码的图像发送到Body of Retrofit POST方法中的服务器

时间:2018-04-18 07:13:40

标签: android-studio post bitmap base64 retrofit2

我的onActivityResult

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

    if (requestCode == CAMERA_INTENT_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getExtras() != null) {



        if (data.getData() == null) {
            bitmap = (Bitmap) data.getExtras().get("data");
            resultImage.setImageBitmap(bitmap);
        } else {
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
                resultImage.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    } else {
        Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
    }
}

转换"位图"到" Base64"

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();

    String convertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

    Log.e("CONVERT IMAGE : ", "" + convertImage);

API调用

  

Content-Type:application / json

JSONObject paramObject = new JSONObject();
 paramObject.put("file", convertImage); //Base64 image
 paramObject.put("userName", name);

Call<Response> addImage = apiInterface.AddImage( user,  paramObject.toString());

POST方法

@POST("{user}/image")
Call<Response> AddImage( @Path("user") String user, @Body String body);

转换后的图片 - 记录结果

E/CONVERT IMAGE :: iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAIAAAD6wG44AAAAA3NCSV...

但我需要传递我的Base64字符串,如下所示,我的字符串缺少数据部分

  

数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAATIAAAExCAY ......

问题是什么?

1 个答案:

答案 0 :(得分:1)

只需在开头

附加data:image/png;base64,即可
 JSONObject paramObject = new JSONObject();
 paramObject.put("file", "data:image/png;base64,"+convertImage); 
 paramObject.put("userName", name);    
 Call<Response> addImage = apiInterface.AddImage( user,  paramObject.toString());