Search code examples
androidpermissionscameramultipart

How to upload a file directly from camera and send it as a multipart without having write or read permissions?


Hi i'm struggling to find a way to upload a file directly form android phone camera to my web server (accept multipart).

Due to regulations in my country for fintech apps, i'm not allowed to ask the user for write and read storage permissions so i have to upload it directly after taking the pictures without saving it in storage.

This is what i currently have.

profileCameraImageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(areAllPermissionsGranted()) {
                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                                profileFile = new File(getActivity().getApplicationContext().getExternalFilesDir(
                                        android.os.Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + "profile.jpg");
                                profileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
                                        authorities,
                                        profileFile);
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, profileUri);
                                startActivityForResult(takePictureIntent, PICK_CAMERA_PROFILE);
                    }    

As well as the multipart creation method, i just passed the profileFile obtained from the code above to here

public MultipartBody.Part prepareFilePartFromCamera(String partName, File file) {

        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
        return body;
    }

Everytime i tried to upload to my webserver, it always tell me that it can't accept the file format. Sometimes i saw that i need write permission in my logcat.

Many thanks for your help


Solution

  • Reading and Writing from external storage needs Permission which is dangerous permission that needs acceptance from the user at runtime.

    The solution for that is to save the image to the internal storage instead of external storage. This does not need permission from the user and you can use it as a file and upload it to the server. this link shows how to save and read the bitmap to the internal storage.