简体   繁体   中英

Uploading image by using Retrofit

I've been trying to upload an image from my application through API. But I keep getting this as response:

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

This is my code:

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();
        }
    }
}

I have tested sending image in Postman 's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

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

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

try this

 @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); 

pass it like this

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

add another part within the multipart request

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

You can use below code for uploading image

First you write code for calling request

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


                }
            });

Then you write code for API

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

Then code for Imagetobody covert is below

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;
}

Try this I had another way to implement

  • Inside your interface

@Multipart
   @POST("edit_profile")
   Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> map);

  • Call in your 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() );
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM