How to get file from 'DocumentFile' and send that file to server using retrofit multipart in Android 10 and above

783 views Asked by At

I am able to open the file explorer and get the file in DocumentFile object but i am stuck with the next step ie. to send the file as multipart.

Step 1: Open the file explorer

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        MainApplication.displayToast(context, "Please install a File Manager.", 1);
    }

Step 2: Get the file in onActivityResult()

DocumentFile documentFile = DocumentFile.fromSingleUri(context, data.getData());

                File file = new File(documentFile.getUri().getPath());
                if(documentFile != null){
                    RequestBody docType = RequestBody.create(MediaType.parse("multipart/form-data"), viewModel.docTypeID.getValue());
                    RequestBody userId = RequestBody.create(MediaType.parse("multipart/form-data"), SharedPrefUtil.getPreference(SharedPrefUtil.USER_ID));
                    RequestBody filename = RequestBody.create(MediaType.parse("multipart/form-data"), documentFile.getName().split("\\.")[0]);

                    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", documentFile.getName(), RequestBody.create(MediaType.parse("/*"), file));

                    viewModel.filePart.setValue(filePart);
                    viewModel.docType.setValue(docType);
                    viewModel.userID.setValue(userId);
                    viewModel.docName.setValue(filename);
                    viewModel.fileName.setValue(documentFile.getName());
                }else {
                    MainApplication.displayToast(context, "Please Select a Document.", 0);
                }

Here in the above step i am not able to send the file as server throws this error FileNotFoundException. open failed: ENOENT (No such file or directory)

0

There are 0 answers