从Google驱动器下载选定的文件 [英] Download selected file from Google drive

查看:199
本文介绍了从Google驱动器下载选定的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有选定文件的驱动器ID,并且可以使用

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);
                }

如何从网址下载文件并保存到SD卡?请帮助我解决这个问题。
Thanks。

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

推荐答案

更新:

其实,你把它写入文件,你不需要'is2Bytes()'。只需将输入流(cont.getInputStream())直接转储到文件即可。

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.

原始答案:

自您指的是 GDAA ,此方法(取自这里)可能适合你:

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;
  }

这是'await'风格的简化版本, UI线程。此外,将输入流转储到缓冲区是可选的,我不知道您的
应用程序的需求是什么。

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.

好运。

这篇关于从Google驱动器下载选定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆