Download selected file from Google drive

时光总嘲笑我的痴心妄想 提交于 2020-01-07 05:31:12

问题


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.


回答1:


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.




回答2:


Use downloadUrl or one of the exportLinks. See https://developers.google.com/drive/v2/reference/files for a description of these properties.



来源:https://stackoverflow.com/questions/31759473/download-selected-file-from-google-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!