How to Pass the image in android using Retrofit?

后端 未结 6 571
一向
一向 2021-01-17 06:03

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

6条回答
  •  逝去的感伤
    2021-01-17 06:36

    Step 1: First initialize service class

    public interface ImageUploadService {  
        @Multipart
        @POST("upload")
        Call 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 call = service.upload(description, body);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call,
                                   Response response) {
                Log.v("Upload", "success");
            }
    
            @Override
            public void onFailure(Call 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

    
    

    In manifest in additon with

    
    

    Refer this.

    You can upload any type of file.

提交回复
热议问题