简体   繁体   English

如何使用Drive.API从Google云端硬盘下载文件?

[英]How to download file from Google Drive using Drive.API?

I am using Google Drive.Api in order to get user's app data synced with users drive account. 我正在使用Google Drive.Api,以使用户的应用程序数据与用户驱动器帐户同步。

The user database is in sqlite database format. 用户数据库为sqlite数据库格式。 I have successfully uploaded the file in binary to the drive but failing to download the file from within the app. 我已成功将二进制文件上传到驱动器,但未能从应用程序内下载文件。

How I get the file URl : 我如何获得文件URl:

  final GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
    credential.setSelectedAccountName(accountName);
    service = new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();

    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, "BackupFile"))
            .build();


    final DriveFolder folder = Drive.DriveApi.getRootFolder(mGoogleApiClient);
    folder.queryChildren(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
            final MetadataBuffer metadataBuffer = metadataBufferResult.getMetadataBuffer();
            int iCount = metadataBuffer.getCount();

            if (iCount == 1) {
                Log.i("Tag", "file was found");
                final DriveId myFileId = metadataBuffer.get(0).getDriveId();
                final DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, myFileId);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DriveResource.MetadataResult mdRslt = file.getMetadata(mGoogleApiClient).await();
                        if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
                            String link = mdRslt.getMetadata().getWebContentLink();
                            Log.d("TAG", "Link to File:" + link);
                             DownloadBackup(link);
                        }
                    }
                }).start();

            }
            metadataBuffer.release();
        }
    });

Trying to download the File via: 尝试通过以下方式下载文件:

public void DownloadBackup(String url){
        InputStream mInput=null;
        FileOutputStream mOutput=null;
        if(url != null && url.length() > 0 ){
        try {
                GoogleAccountCredential crd = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
                crd.setSelectedAccountName(accountName);
                com.google.api.services.drive.Drive srv = new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), crd).build();
                mInput = srv.getRequestFactory().buildGetRequest(new GenericUrl(url)).execute().getContent();
                String outFileName = getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME).getPath();
                mOutput = new FileOutputStream(outFileName);
                byte[] mBuffer = new byte[1024];
                int mLength;
                while ((mLength = mInput.read(mBuffer)) > 0) {
                    mOutput.write(mBuffer, 0, mLength);
                }
                mOutput.flush();
                Log.d("TAG", "Successfully Downloaded contents");
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    //Close the streams
                    if(mOutput != null){
                        mOutput.close();
                    }
                    if(mInput != null){
                        mInput.close();
                    }
                } catch (IOException e) {
                    Log.e("Tag", "failed to close databases");
                }
            }
        } else {
            // The file doesn't have any content stored on Drive.
            // return null;
            Log.e("Tag", "No content on Drive");
        }
    }

Error Log: 错误日志:

W/System.err﹕ com.google.api.client.http.HttpResponseException: 401 Unauthorized
W/System.err﹕ <HTML>
W/System.err﹕ <HEAD>
W/System.err﹕ <TITLE>Unauthorized</TITLE>
W/System.err﹕ </HEAD>
W/System.err﹕ <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
W/System.err﹕ <H1>Unauthorized</H1>
W/System.err﹕ <H2>Error 401</H2>
W/System.err﹕ </BODY>
W/System.err﹕ </HTML>
W/System.err﹕ [ 06-12 11:01:05.447 26208:26236 W/System.err ]
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1061)
W/System.err﹕ at com.example.app.activities.Main.DownloadBackup(Main.java:487)
W/System.err﹕ at com.example.app.activities.Main$15$1.run(Main.java:332)
W/System.err﹕ at java.lang.Thread.run(Thread.java:841)

Here is how I do it successfully. 这是我成功完成的方法。 Instead of saving the result of 'getWebContentLink', I save a file/folder ID (it is a string). 我没有保存“ getWebContentLink”的结果,而是保存了文件/文件夹ID(它是一个字符串)。 And pass this ID to a method like this one: 并将此ID传递给这样的方法:

 /*************************************************************************
   * get file contents
   * @param resId  file driveId
   * @return       file's content  / null on fail
   */
  static InputStream read(String resId) {
    if (mGOOSvc != null && mConnected && resId != null) try {
      File gFl = mGOOSvc.files().get(resId).setFields("downloadUrl").execute();
      if (gFl != null){
        String strUrl = gFl.getDownloadUrl();
        return mGOOSvc.getRequestFactory()
        .buildGetRequest(new GenericUrl(strUrl)).execute().getContent();
      }
    } catch (Exception e) { /* error handling */ }
    return null;
  }

retrieving a "downloadURL" and get the content. 检索“ downloadURL”并获取内容。 The full context of this method can be seen here . 这里可以看到此方法的完整上下文。

Good Luck 祝好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Android Studio 中使用 Google Drive API 从驱动器下载文件以上传到另一个驱动器 - Download file from drive to upload into another drive using Google Drive API in Android Studio 从Google Drive API下载任何文件 - Download any file from Google Drive API 使用google-api-services-drive:v3从google驱动器下载文件 - Download file from google drive using google-api-services-drive:v3 如何使用Drive API下载Google Doc,电子表格和Presentation文件? - How to download Google Doc, Spreadsheet and Presentation file by using Drive API? 无法添加Google Drive Drive.API,Google授权工作正常 - Cannot add Google Drive Drive.API, Google authorization worked fine Google Drive Android Drive.API Android可以与其他API结合使用吗? - Can Google Drive Android Drive.API Android be combined with other API's? 如何使用Google Drive Android API删除Google Drive上的文件 - How to delete a file on google drive using Google Drive Android API 如何使用 Google Drive API 从 android 将加密的图像文件上传到 Google Drive - How to upload encrypted image file on google drive from android using Google Drive API 我必须为Drive.API和Auth.GOOGLE_SIGN_IN_API创建2个Google Api客户端吗? - Do i have to create 2 Google Api Client for Drive.API and Auth.GOOGLE_SIGN_IN_API? 从带有URI的Google云端硬盘下载文件,而无需Android中的Google云端硬盘API - Download file from Google Drive with its URI, without Google Drive API in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM