使用Retrofit上传图像

时间:2017-11-15 04:35:27

标签: java android retrofit2

我一直在尝试通过API从我的应用程序上传图像。但我一直把这个作为回应:

{"error":"<p>You did not select a file to upload.<\/p>"}

这是我的代码:

APIService.java

@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);

UploadImageActivity.java

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

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

我已经测试了在 Postman 的表单数据中发送图片。我可以从桌面发送图片并收到预期的回复。但我不能用我在Android中的代码做同样的事情。

我是否发送了错误的图片路径格式?目前,变量imagePath的输出如下:

/storage/emulated/0/Download/download.jpg

如果这是不正确的发送路径,请说出正确的路径。提前谢谢。

3 个答案:

答案 0 :(得分:0)

试试这个

 @Multipart @POST("user/updateprofile") Observable<ResponseBody>
 updateProfile(@Part("user_id") RequestBody id, @Part("full_name")
 RequestBody fullName, @Part MultipartBody.Part image, @Part("other")
 RequestBody other); 

像这样传递

File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

在多部分请求中添加另一部分

 RequestBody fullName =  RequestBody.create(  MediaType.parse("multipart/form-data"), "Your Name");
 service.updateProfile(id, fullName, body, other)

答案 1 :(得分:0)

您可以使用以下代码上传图片

首先编写调用请求的代码

//profile pic is image path
    RequestBody imagePath = Utility.imageToBody(profilePic);

 TestApiInterface service = WebServiceCaller.getClient();
 Call<SuccessResponse> call = service.mediaUpload(imagePath);

 call.enqueue(new Callback<SuccessResponse>() {
                @Override
                public void onResponse(Call<SuccessResponse> call, 
 Response<SuccessResponse> response) {
                    SuccessResponse result;
                    if (response.isSuccessful()) {
                        result = response.body();

                     }
                }

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


                }
            });

然后你编写API的代码

@Multipart
@POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(@Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);

然后,Imagetobody隐藏的代码在

之下
public static RequestBody imageToBody(String text) {
    RequestBody requestBody;
    if (text != null && text.length() > 0) {
        MediaType MEDIA_TYPE = MediaType.parse("image/*");
        File file = new File(text);
        requestBody = RequestBody.create(MEDIA_TYPE, file);
    } else {
        requestBody = null;
    }
    return requestBody;
}

答案 2 :(得分:0)

试试这个我有另一种方法来实现

  • interface
@Multipart
   @POST("edit_profile")
   Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> map);
  • 致电Activity
private void getData() {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("your_base_url_here")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Click service=retrofit.create(Click.class);
          File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
          //make sure your image path is valid
        String convert_File_2String= String.valueOf(file);
        String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
        RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
        Map<String, RequestBody> map = new HashMap<>();
        map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
        map.put("firstname", name);
        map.put("user_id", id);
        map.put("lastname",lastname);

    Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
    tokenResponseCall.enqueue(new Callback<TokenResponse>() {
        @Override
        public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
            TokenResponse tokenResponse=response.body();
            Log.e("93","MA>>"+tokenResponse.getJwt());
                  }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<TokenResponse> call, Throwable throwable) {
                    Log.e("172","><<>>"+throwable);
            Log.e("TAG", "onFailure: 173"+call.toString() );
        }
    });
}