Search code examples
androidinputstreamfilepicker

Android attachment / file picker into InputStream string


I want to create a similar function as below image. Allow user to select image / pdf file from device and convert the file into inputstream as string and sent to server.
I had go through this Attaching a file of any type in Android application? and successfully to call for document but does not have option for camera. Appreciate if there any source i can refer or library that able to perform this:

  • provide option to select from gallery/take new photo/document
  • Select file and convert to string (inputstream)

    enter image description here

    //Json that server going to receive
    "Attachment": {
    "InputStream": "string",
    "FileName": "string"
    }
    
    
    /*My Code*/
    public void goToAttachment(){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*|application/pdf");
        startActivityForResult(Intent.createChooser(intent, null), SELECTFILE_RESULT_CODE);
    
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        switch (requestCode){
            case SELECTFILE_RESULT_CODE:
                if(resultCode == RESULT_OK){
                    fileSrc = data.getData().getPath();
    
                }
                break;
        }
    }
    

  • Solution

  • You can use below code to get first Bitmap of Image and then get String from Bitmap Object:

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        switch (requestCode){
            case SELECTFILE_RESULT_CODE:
                if(resultCode == RESULT_OK){
              // Let's read picked image data - its URI
            Uri pickedImage = data.getData();
            // Let's read picked image path using content resolver
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
            String bmpString= bitMapToString(bitmap)
            cursor.close();
            }
            break;
        }
    }
    

    You can use below method to convert Bitmap to String:

    public String bitMapToString(Bitmap bitmap){
         ByteArrayOutputStream baos=new  ByteArrayOutputStream();
         bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
         byte [] b=baos.toByteArray();
         String temp=Base64.encodeToString(b, Base64.DEFAULT);
         return temp;
    }
    

    you can change Bitmap Compress format JPG or PNG as par your image.

    For PDF and other file you can use below method to convert it into String.

    private String getString(String filepath) throws IOException {
                InputStream inputStream = new FileInputStream(filepath);
                byte[] byteArray = IOUtils.toByteArray(inputStream);
                String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
                return encoded;
            }
    

    To get File path you can use bellow code:

    public String getRealPathFromURI(Context context, Uri contentUri) {
      Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }