简体   繁体   中英

Facing Issue while uploading images using android Retrofit 2

i am having some issues regarding upload image using retrofit 2 . i have an api to upload three kind of images like(Profile images , Banner images , Other images). i need to pass three parameters (user_id , type(profile / banner / other) , media(file) )... i am not understanding how to do it ...

here is my interface...

@Multipart
    @POST("media/upload_media")
    Call<ServerRespose> upload(
            @Part MultipartBody.Part file ,
            @Query("user_id") int user_id ,
            @Query("type") String type
    );

and here is my coe where i am trying to do it...

 private void uploadFile(String path, Uri fileUri, final int type) {
        // create upload service client

        uid = DatabaseUtil.getInstance().getUser().getData().getID();
        String username = SharedPreferenceUtil.getStringValue(this, Constants.USERNAME);
        String password = SharedPreferenceUtil.getStringValue(this, Constants.PASSWORD);


        if (!username.isEmpty() && !password.isEmpty()) {
            Api service =
                    RetrofitUtil.createProviderAPIV2(username, password);

            //
            try {
                // use the FileUtils to get the actual file by uri
                showProgressDialog("Uploading");
                File file = new File(path);

                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("file", file.getName(), requestFile);

                // finally, execute the request
                Call<ServerRespose> call = service.upload(body  , uid , "profile_image");
                call.enqueue(new Callback<ServerRespose>() {
                    @Override
                    public void onResponse(Call<ServerRespose> call,
                                           Response<ServerRespose> response) {
                        hideProgressDialog();
                        Log.v("Upload", "success");
                        ServerRespose item = response.body();
                        try {
                            if (item != null) {

    //                            item.setSuccess(true);
                                if (type == SELECT_PROFILE_PIC) {
                                    profileImageRecyclerViewAdapter.addNewItem(item);
                                    profileImageRecyclerViewAdapter.notifyDataSetChanged();
                                } else {
                                    bannerImageRecyclerViewAdapter.addNewItem(item);
                                    bannerImageRecyclerViewAdapter.notifyDataSetChanged();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ServerRespose> call, Throwable t) {
                        AppUtils.showDialog(Profile_Activity.this, "There is some Error", null);
                        Log.e("Upload error:", t.getMessage());
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showDialogSignedUp("Session Expired Please Login Again...", null);
        }
    }

Note: My code is not working just pick image and showing uploading and it is also not returning any kind of response ... Any one please help with the correct code i need to do this work on a very short notice. check the parameters here...

 function save_image($request)
        {
            if(!empty($request['user_id'])){
                $user_identity  = $request['user_id'];
                $submitted_file = $_FILES['media'];

                $uploaded_image = wp_handle_upload( $submitted_file, array( 'test_form' => false ) );
                $type = $request[ 'type' ];
                //return $submitted_file;
                if ( !empty( $submitted_file )) {
                    $file_name = basename( $submitted_file[ 'name' ] );
                    $file_type = wp_check_filetype( $uploaded_image[ 'file' ] );

                    // Prepare an array of post data for the attachment.
                    $attachment_details = array(
                        'guid' => $uploaded_image[ 'url' ],
                        'post_mime_type' => $file_type[ 'type' ],
                        'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
                        'post_content' => '',
                        'post_status' => 'inherit'
                    );

Try this way..

@Multipart
@POST(NetworkConstants.WS_REGISTER)
Call<UserResponseVo> registerUser(@Part MultipartBody.Part file, @PartMap Map<String, RequestBody> map);

after that..

 MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);


    RequestBody userName = RequestBody.create(MediaType.parse("text"), mEtUserName.getText().toString());
    RequestBody userEmail = RequestBody.create(MediaType.parse("text"), mEtEmail.getText().toString().trim());
    RequestBody userPassword = RequestBody.create(MediaType.parse("text"), mEtPassword.getText().toString().trim());

    Map<String, RequestBody> map = new HashMap<>();
    map.put(NetworkConstants.KEY_FIRST_NAME, userName);
    map.put(NetworkConstants.KEY_EMAIL, userEmail);
    map.put(NetworkConstants.KEY_PASSWORD, userPassword);

retrofit.create(ApiInterface.class).registerUser(fileToUpload, map);

Try this

1)Declare method in interface class

  @Multipart
    @POST("media/upload_media")
    Call<AddImageResponseClass> upload(@Part("user_id") RequestBody user_id, @Part("media\"; filename=\"myfile.jpg\" ") RequestBody profile_pic,@Part("type") RequestBody type);

Then in java class

 String BASE_URL=base_url;

final OkHttpClient okHttpClient = new OkHttpClient.Builder().writeTimeout(2, TimeUnit.MINUTES).retryOnConnectionFailure(true)
                .readTimeout(2, TimeUnit.MINUTES)
                .connectTimeout(2, TimeUnit.MINUTES)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL).client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
      Api service =
                RetrofitUtil.createProviderAPIV2(username, password);

 File file = new File(path);
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file );
        String user_id= user_id_here;
        String type= type_here;
        RequestBody reqUserId= RequestBody.create(MediaType.parse("text/plain"), user_id);
 RequestBody reqType= RequestBody.create(MediaType.parse("text/plain"), type);
        Call<ServerRespose> userCall = service.upload(reqUserId, reqFile,reqType);
        userCall.enqueue(new Callback<ServerRespose>() {
            @Override
            public void onResponse(Call<ServerRespose> call, Response<ServerRespose> response) {

                    if (response.body() == null) {
                      //handle here
                        return;
                    }



            }

            @Override
            public void onFailure(Call<ServerRespose> call, Throwable t) {
                System.out.println("response failure" + t.getMessage());
                t.printStackTrace();
            }
        });

And import these

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

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