You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API让用户输入凭证实现Google Drive文件上传?

Google Drive 上传功能最简实现方案(面向非技术用户)

核心思路

针对非技术用户,采用OAuth 2.0 桌面应用授权流程是最优解:用户只需在Google Cloud控制台生成简单凭证,通过工具引导完成一次授权,即可得到可长期复用的刷新令牌(Refresh Token),后续上传无需重复授权。

用户侧凭证生成步骤(非技术友好)

  • 打开Google Cloud控制台,创建新项目(或使用现有项目)
  • 搜索并启用「Google Drive API」
  • 进入「API和服务」→「凭据」页面,点击「创建凭据」→「OAuth 客户端ID」
  • 应用类型选择「桌面应用」,填写任意名称后完成创建,下载生成的JSON文件
  • 打开你的工具,点击「生成Refresh Token」按钮,选择下载的JSON文件,工具会自动打开浏览器引导你完成Google账号授权,授权后工具会提取并展示Client ID、Client Secret、Refresh Token,将这三个值保存到工具UI中即可

Java 实现核心代码

1. 依赖引入(Maven)

<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-java6</artifactId>
    <version>1.34.1</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v3-rev20240425-2.0.0</version>
</dependency>

2. 认证与上传逻辑

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class GoogleDriveUploader {
    private static final String APP_NAME = "你的工具名称";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final List<String> UPLOAD_SCOPES = Collections.singletonList(DriveScopes.DRIVE_FILE);

    // 生成Refresh Token(用户首次授权用)
    public static Credential generateRefreshToken(String clientId, String clientSecret) throws IOException {
        GoogleClientSecrets.Details details = new GoogleClientSecrets.Details();
        details.setClientId(clientId);
        details.setClientSecret(clientSecret);
        GoogleClientSecrets clientSecrets = new GoogleClientSecrets().setInstalled(details);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, UPLOAD_SCOPES)
                .setAccessType("offline") // 必须设置才能获取Refresh Token
                .build();
        
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    // 通过已有Refresh Token创建认证凭证
    private static Credential getCredentialFromRefreshToken(String clientId, String clientSecret, String refreshToken) throws IOException {
        Credential credential = new Credential.Builder(com.google.api.client.auth.oauth2.BearerToken.authorizationHeaderAccessMethod())
                .setTransport(GoogleNetHttpTransport.newTrustedTransport())
                .setJsonFactory(JSON_FACTORY)
                .setTokenServerUrl(new com.google.api.client.http.GenericUrl("https://oauth2.googleapis.com/token"))
                .setClientAuthentication(new com.google.api.client.googleapis.auth.oauth2.GoogleClientAuthentication(clientId, clientSecret))
                .build();
        
        credential.setRefreshToken(refreshToken);
        credential.refreshToken(); // 自动获取有效Access Token
        return credential;
    }

    // 上传图片到Google Drive
    public static String uploadImage(String imagePath, String clientId, String clientSecret, String refreshToken) throws IOException, GeneralSecurityException {
        Drive driveService = new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, 
                getCredentialFromRefreshToken(clientId, clientSecret, refreshToken))
                .setApplicationName(APP_NAME)
                .build();

        File fileMetadata = new File();
        fileMetadata.setName(new java.io.File(imagePath).getName());
        // 可选:指定上传到特定文件夹,替换为你的文件夹ID
        // fileMetadata.setParents(Collections.singletonList("your-folder-id"));

        com.google.api.client.http.FileContent mediaContent = new com.google.api.client.http.FileContent("image/jpeg", new java.io.File(imagePath));
        File uploadedFile = driveService.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();

        return uploadedFile.getId(); // 返回上传后的文件ID,可用于后续访问
    }
}

3. UI交互建议

  • 提供三个输入框:Client ID、Client Secret、Refresh Token
  • 添加「生成Refresh Token」按钮:点击后让用户选择从Google Cloud下载的JSON文件,工具解析出Client ID和Client Secret,调用generateRefreshToken方法打开浏览器授权,授权成功后自动填充三个输入框
  • 上传按钮:调用uploadImage方法,传入用户输入的三个凭证参数和图片路径

内容的提问来源于stack exchange,提问作者Mike Q

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:55:18