get path from Google Drive URI

后端 未结 3 903
庸人自扰
庸人自扰 2021-02-04 11:49

I\'m using Android file selection and selecting files from app storage (images, videos, documents). I have an function \"getPath\" . Im getting path from uri. I have no problem

3条回答
  •  清酒与你
    2021-02-04 12:04

    I was also stuck with the same issue and found that when we choose image from google drive its uri is like below

    com.google.android.apps.docs.storage
    

    and we cant directly get the path of file as it is not in our device. So we first download the file to a certain destination and then we can use that path to do our work. Below is the code for the same

    FileOutputStream fos = null;
        try {
             fos = new FileOutputStream(getDestinationFilePath());
             try (BufferedOutputStream out = new BufferedOutputStream(fos); 
             InputStream in = mContext.getContentResolver().openInputStream(uri)) 
               {
                byte[] buffer = new byte[8192];
                int len = 0;
    
                while ((len = in.read(buffer)) >= 0) {
                      out.write(buffer, 0, len);
                     }
    
                 out.flush();
                } finally {
                           fos.getFD().sync();
                          }
    
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
    
                File file = new File(destinationFilePath);
                if (Integer.parseInt(String.valueOf(file.length() / 1024)) > 1024) {
                InputStream imageStream = null;
    
    
    
                try {
                     imageStream = mContext.getContentResolver().openInputStream(uri);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
    

    now your file is saved at the desired destination path and you can use it.

提交回复
热议问题