如何使用Java中的Google Drive API库强制从Google Team Drive下载文件 [英] How to force download of file from Google Team Drive using Google Drive API libraries in Java

查看:289
本文介绍了如何使用Java中的Google Drive API库强制从Google Team Drive下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,当用户点击我的应用程序中表单上的链接时,我试图强制从Google Team Drive下载文件。

In my application, I am trying to force a download of a file from a Google Team Drive when the user clicks on a link on a form in my application.

一些更新:


  1. 我的代码可以上传到Team Drive,也可以在Team Drive上创建文件夹。

  1. I have code that can upload to the Team Drive as well as create folders on the Team Drive.

Team Drives支持 - 此应用程序可与Team Drives中的文件一起正常运行。无法启用Google Drive API设置 - 我可以选中此框,但我无法点击保存更改按钮,因为该按钮始终处于禁用状态。但是,我不认为这是问题,因为我可以在我的代码中与团队驱动器进行交互。

The "Team Drives support - This application works properly with files in Team Drives." on the Google Drive API settings CANNOT be enabled - I can check this box, but I cannot click the Save Changes button, since the button is always disabled. However, I don't think that is the issue, since I can interact with the Team Drive in my code.

我已阅读Google文档,该文档非常有限:

I have read the Google documentation, which is very limited:

https://developers.google.com/drive/v3/web/manage-downloads

https://developers.google.com/drive/v3/reference/files/get

我还读了几篇文章:

使用java API从谷歌驱动器下载文件

但是,我找不到有效的答案。我已经构建了一些使用服务帐户的代码。代码设置驱动器服务并使用服务帐户作为凭据。我根据此Google文档示例提供了代码的下载部分:

But, I can't find an answer that works. I have built some code which uses a Service Account. The code sets the drive service and uses the Service Account as the credentials. I based the download part of my code from this Google documentation example:

https://developers.google.com/drive/v3/web/manage-downloads#examples

以下是我正在使用的代码:

Here is the code I am using:

public static void downloadFile(String fileID) {
    // Set the drive service...
    Drive service = null;
    try {
        service = getDriveService();
    } catch (IOException e) {
        e.printStackTrace();
    }
    OutputStream outputStream = new ByteArrayOutputStream();
    try {
        service.files().get(fileID).executeMediaAndDownloadTo(outputStream);
        // NEED CODE HERE???????


    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Build and return an authorized Drive client service.
 * 
 * @return an authorized Drive client service
 * @throws IOException
 */
public static Drive getDriveService() throws IOException {
    Logger.info("GoogleDrive: getDriveService: Starting...");
    GoogleCredential credential = null;
    Drive googleDrive = null;
    try {
        credential = authorize();
        Logger.info("GoogleDrive: getDriveService: Credentials set...");
        googleDrive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
    } catch (IOException ex) {
        System.out.println(ex.toString());
        ex.printStackTrace();
    }
    return googleDrive;
}

/**
 * Creates an authorized Credential object.
 * 
 * @return an authorized Credential object.
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public static GoogleCredential authorize() throws IOException {
    GoogleCredential credential = null;
    String credentialsFileName = "";
    try {
        Logger.info("GoogleDrive: authorize: Starting...");

        Logger.info("GoogleDrive: authorize: Getting credentialsFileName path...");
        credentialsFileName = Configuration.root().getString("google.drive.credentials.file");
        Logger.info("GoogleDrive: authorize: credentialsFileName = " + credentialsFileName);

        Logger.info("GoogleDrive: authorize: Setting InputStream...");
        InputStream in = GoogleDrive.class.getClassLoader().getResourceAsStream(credentialsFileName);
        if (in == null) {
            Logger.info("GoogleDrive: authorize: InputStream is null");
        }
        Logger.info("GoogleDrive: authorize: InputStream set...");

        Logger.info("GoogleDrive: authorize: Setting credential...");
        credential = GoogleCredential.fromStream(in, HTTP_TRANSPORT, JSON_FACTORY)
                .createScoped(Collections.singleton(DriveScopes.DRIVE));
    } catch (IOException ex) {
        System.out.println(ex.toString());
        System.out.println("Could not find file " + credentialsFileName);
        ex.printStackTrace();
    }
    Logger.info("GoogleDrive: authorize: Ending...");
    return credential;
}

当我的代码运行时,没有错误,也没有任何反应。我猜我在downloadFile函数中缺少一些代码。如果我在编码中遗漏了某些内容或不正确,请随时提供我应该使用的示例或正确的代码。

When my code runs, there are no errors and nothing happens. I am guessing I am missing some code in the downloadFile function. If I am missing something or incorrect in my coding, please feel free to provide examples or the correct code I should be using.

我感谢您的帮助。

推荐答案

此演示不使用服务帐户。

我将演示如何下载团队驱动器文件,并希望它能让您深入了解您的项目。

I'm just going to demonstrate how I downloaded a Team drive file and hopefully it gives you insight on your project.

代码的基础取自 Drive API Java快速入门

public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

       //this is what you're looking for - a way to download a file using 'webContentLink'
        try {        
              Desktop desktop = java.awt.Desktop.getDesktop();
              //place your webContentLink in the oURL variable
              URI oURL = new URI("https://drive.google.com/a/google.com/uc?id=YOUR_FILE_ID&export=download");
              desktop.browse(oURL);

        } catch (Exception e) {
            e.printStackTrace();
        }
}

执行时,此程序会打开一个空白的浏览器窗口,将文件下载到您的计算机。

Upon execution, this program opens a blank browser window and downloads the file to your computer.

我生成 webContentLink 的方式只是使用 Files.get试一试并确保我设置 supportsTeamDrives true 并将 fields 参数设置为 webContentLink 所以它只返回。

The way I generated the webContentLink was just use the Files.get Try-it and made sure I set supportsTeamDrives to true and also setting fields parameter to webContentLink so it returns just that.

当然,您始终可以通过编程方式使用Java files.get 来获取 webContentLink 但使用Try-it获取 webContentLink 更容易进行测试。

Of course you can always use the Java files.get programmatically to fetch webContentLink but fetching the webContentLink using the Try-it was easier for testing purposes.

这篇关于如何使用Java中的Google Drive API库强制从Google Team Drive下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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