Search code examples
androidgoogle-drive-apigoogle-drive-android-api

Download selected file from Google drive


I have Drive Id of selected file and I am able to get Url of that file using

MetadataResult mdRslt;
        DriveFile file;
    file = Drive.DriveApi.getFile(mGoogleApiClient,driveId);
                mdRslt = file.getMetadata(mGoogleApiClient).await();
                if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
                    link = mdRslt.getMetadata().getWebContentLink();
                    if(link==null){
                        link = mdRslt.getMetadata().getAlternateLink();
                        Log.e("LINK","FILE URL After Null: "+ link);
                    }
                    Log.e("LINK","FILE URL : "+ link);
                }

How to download file from url and save in to SD card? Please help me regarding this. Thanks.


Solution

  • UPDATE:
    Actually, since you writing it to a file, you don't need the 'is2Bytes()'. Just dump the input stream (cont.getInputStream()) directly to a file.

    ORIGINAL ANSWER:
    Since you are referring to the GDAA, this method (taken from here) may just work for you:

      GoogleApiClient mGAC;
    
      byte[] read(DriveId id) {
        byte[] buf = null;
        if (mGAC != null && mGAC.isConnected() && id != null) try {
          DriveFile df = Drive.DriveApi.getFile(mGAC, id);
          DriveContentsResult rslt = df.open(mGAC, DriveFile.MODE_READ_ONLY, null).await();
          if ((rslt != null) && rslt.getStatus().isSuccess()) {
            DriveContents cont = rslt.getDriveContents();
            buf = is2Bytes(cont.getInputStream());
            cont.discard(mGAC);    // or cont.commit();  they are equiv if READONLY
          }
        } catch (Exception e) { Log.e("_", Log.getStackTraceString(e)); }
        return buf;
      }
    
      byte[] is2Bytes(InputStream is) {
        byte[] buf = null;
        BufferedInputStream bufIS = null;
        if (is != null) try {
          ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
          bufIS = new BufferedInputStream(is);
          buf = new byte[4096];
          int cnt;
          while ((cnt = bufIS.read(buf)) >= 0) {
            byteBuffer.write(buf, 0, cnt);
          }
          buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
        } catch (Exception ignore) {}
        finally {
          try {
            if (bufIS != null) bufIS.close();
          } catch (Exception ignore) {}
        }
        return buf;
      }
    

    It is a simplified version of 'await' flavor that has be run off-UI-thread. Also, dumping input stream into a buffer is optional, I don't know what your app's needs are.

    Good Luck.