How to Pass the image in android using Retrofit?

﹥>﹥吖頭↗ 提交于 2019-12-30 15:42:00

问题


Hello i am working on upload image file using retrofit. Can any one have idea how to pass in


回答1:


You need pass mulitypart object in retrofit:

MultipartBody.Part carImage = null;
    if (!TextUtils.isEmpty(imagePath)) {
        File file = FileUtils.getFile(getContext(), imagePath);
        // create RequestBody instance from file
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        // MultipartBody.Part is used to send also the actual file name
        carImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
    }



回答2:


public static MultipartBody.Part UploadImage(String filePath,String param) {

   MultipartBody.Part body = null;
    try {
        body = MultipartBody.Part.createFormData("", "", null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //profileUpdateRequest.setWebsite(lblWebsite.getText().toString().trim());
    if ((!filePath.equals(""))) {
        File file = new File(filePath);
        RequestBody photo = RequestBody.create(MediaType.parse("image/*"), file);
        body = MultipartBody.Part.createFormData(param, file.getName(), photo);
    }
    return body;

}

Step::1Pass the file Path and it will return you MultiPart body

@Multipart
@POST(Endpoint.POST_URL)
Call<DecisionStepThirdResponse> uploadUserProfile(@Part("api_id") RequestBody api_id,
                                                @Part("api_secret") RequestBody api_secret,
                                                @Part("api_request") RequestBody api_request,
                                                @Part("data") RequestBody data,
                                                @Part MultipartBody.Part profile_image);

========================

Step 2: Pass the Request like this

 public void uploadUserProfile(UpdateImageRequest request, MultipartBody.Part file, Callback<UpdateImageResponse> callback) {
    String api_request = "uploadUserProfile";
    String data = new Gson().toJson(request);
    IRoidAppHelper.Log("application_form_permission", data);
    json().uploadUserProfile(
            RequestBody.create(MediaType.parse("text/plain"), api_id),
            RequestBody.create(MediaType.parse("text/plain"), api_secret),
            RequestBody.create(MediaType.parse("text/plain"), api_request),
            RequestBody.create(MediaType.parse("text/plain"), data)
            , file).enqueue(callback);
}

Step 3 : And Pass the Parameter in your Serviceclass




回答3:


Please go through the following link.




回答4:


Have time to refer this link :)

https://medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c#.iinz6neii




回答5:


Step 1: First initialize service class

public interface ImageUploadService {  
    @Multipart
    @POST("upload")
    Call<ResponseBody> upload(
        @Part("description") RequestBody description,
        @Part MultipartBody.Part file
    );
}

Step 2: in next step use this where you want to upload image or file

private void uploadFile(Uri fileUri) {  
    // create upload service client
    FileUploadService service =
            ServiceGenerator.createService(ImageUploadService.class);

    // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
    // use the FileUtils to get the actual file by uri
    File file = FileUtils.getFile(this, fileUri);

    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(
                         MediaType.parse(getContentResolver().getType(fileUri)),
                         file
             );

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

    // add another part within the multipart request
    String descriptionString = "hello, this is description speaking";
    RequestBody description =
            RequestBody.create(
                    okhttp3.MultipartBody.FORM, descriptionString);

    // finally, execute the request
    Call<ResponseBody> call = service.upload(description, body);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,
                               Response<ResponseBody> response) {
            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("Upload error:", t.getMessage());
        }
    });
}

Step 3: you can use like this

uploadFile(Uri.fromFile(new File("/sdcard/cats.jpg")));

In your activity.

Last step: you need to add

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

In manifest in additon with

<uses-permission android:name="android.permission.INTERNET"/>

Refer this.

You can upload any type of file.




回答6:


/* Create interface like below. */

public interface uploadWishImage {

    @Multipart
    @POST("upload/image")
    Call<JsonObject> postImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
}

/* image upload code */

  File file = new File("here your file path");
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "file");
        uploadWishImage postService = RetrofitApi.makeNetworkRequestWithHeaders(AddWish.this).create(uploadWishImage.class);
        Call<JsonObject> call = postService.postImage(body, name);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
               // somethings to do with reponse

            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                // Log error here since request failed



            }
        });


来源:https://stackoverflow.com/questions/42290720/how-to-pass-the-image-in-android-using-retrofit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!