Search code examples
androidimagefileretrofitmultipart

File upload by MultipartBody.Part


I'm using retrofit 2 to upload my files, a problem i got my self into is that when I'm trying to get the file from the URI I get error:

W/System.err: stat failed: ENOENT (No such file or directory) : /external/images/media/1838
          stat failed: ENOENT (No such file or directory) : /external/images/media/1838
          stat failed: ENOENT (No such file or directory) : /external/images/media/1838

and I'm getting that error in an infinite loop in my log. the code I wrote for getting the image from gallery:

        imageViewUpdateProfileActivity.setOnClickListener(view -> {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);
    });

and for getting it in onActivityResult:

    @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK) {
        File file = new File(Objects.requireNonNull(Objects.requireNonNull(data).getData()).getPath());
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        RequestBody fullname = RequestBody.create(MediaType.parse("text/plain"), editTextFullNameUpdateProfileActivity.getText().toString());
        RequestBody Gender = RequestBody.create(MediaType.parse("text/plain"), gender);
        RequestBody aboutMe = RequestBody.create(MediaType.parse("text/plain"), editTextAboutMeUpdateProfileActivity.getText().toString());

        ApiClient.getClient().create(ApiService.class).updateProfilePhoto(App.userProfile.getUsername(), filePart, fullname, Gender, aboutMe).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}

Solution

  • Follow this below two methods. Here is the full tutorial link

     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == 0 && resultCode == RESULT_OK && null != data) {
    
                // Get the Image from data
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
    
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();
    
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mediaPath = cursor.getString(columnIndex);
                // Set the Image in ImageView for Previewing the Media
                imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();
    
            } else {
                Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }
    
    }
    
    
    
    // Uploading Image/Video
    private void uploadFile() {
        progressDialog.show();
    
        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
    
        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
    
        ApiService getResponse = ApiClient.getClient().create(ApiService.class);
        Call<ServerResponse> call = getResponse.uploadFile(fileToUpload, filename);
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }
    
            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
    
            }
        });
    }