通过使用Java 来整合 Google Drive 实现文件上传

通过使用Java 来整合 Google Drive

 

由于最近需要使用到Google Drive 作为上传文件的一个容器,所以整合了一个小的Demo来上传文件到对应的Google Drive 文件夹上面。

下面采用Java 语言的方式来描述代码的结构,在其他语言上面也是一样的逻辑思路。

采用的Spring + Maven 结构来构建工程。

能看到这篇文章,相信你可以进行科学上网了;

第一步:在google Drive 可以创建一个对应的项目:

 链接地址: https://console.cloud.google.com/home/dashboard?

然后你将看到一个对应项目

第二步:给调用的应用创建凭证,需要进到刚刚创建的项目里面进行,找到API和服务 -> 凭据

 

 

这里可以选择很多种方式进行认证授权,由于我是通过服务端对接的,所以我选择了服务账号方式进行整合,如果你需要授权用户的方式的话 你可以使用OAuth2 方式,这个方式会有个授权的界面,这里我就不描述了。

 

最后可以点击进去里面创建 私钥:

 

这里创建私钥我建议使用JSON的方式(至于为什么嘛~~~ 哈哈 比较熟悉语语言)  我这里也是使用JSON的格式

下载下来 打开应该就这样了

好的,我们现在执行我们最重要的一步了:

就是我们需要 https://console.cloud.google.com/apis/library 进入到应用里面开启Google Drive 对应的API 功能

 

 

第三步: 需要去到Google Drive 文件管理上面找到我们需要操作的文件夹,然后点击共享把服务账号添加进去,

       

 

然后就可以了,如果后面需要控制权限可以去服务账号的页面进行调整。。。。。。

 

 

做到这个我们就准备的差不多了;

下面就准备一个工程项目:

第一步 加入Maven

<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-drive -->
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-drive</artifactId>
            <version>v3-rev188-1.25.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.30.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client-jetty</artifactId>
            <version>1.30.5</version>
        </dependency>

        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>0.20.0</version>
        </dependency>

 

第二步 : 我这里采用的使用配置文件的方式配置进行,下面我也会说下直接部署json 文件

在yml 下面 :

google-drive:
  type: service_xxx
  project_id: xxx
  private_key_id: xxxx
  private_key: "xxxx"
  client_email: xxxxxx
  client_id: xxx
  auth_uri: https://accounts.google.com/o/oauth2/auth
  token_uri: https://oauth2.googleapis.com/token
  auth_provider_x509_cert_url: xxxxx
  client_x509_cert_url: xxx

这里有个小细节需要注意的,在添加private_key的时候我们需要使用双引号加上。这里使用过Spring security的话应该有过这种经历:

下面我们直接通过spring 的方式加入

@Data
@Configuration
@ConfigurationProperties(prefix = "google-drive")
public class GoogleDriveConfiguration implements Serializable {
    private String type;
    private String project_id;
    private String private_key_id;
    private String private_key;
    private String client_email;
    private String client_id;
    private String auth_uri;
    private String token_uri;
    private String auth_provider_x509_cert_url;
    private String client_x509_cert_url;
}

这一步我们就可以通过在整一个spring的周期使用到它了;

 

 

第三步:我们需要创建操作 Google Drive service 类

 @Autowired
 private GoogleDriveConfiguration googleDriveConfiguration;

GoogleDriveConfiguration configuration = new GoogleDriveConfiguration();
BeanUtils.copyProperties(googleDriveConfiguration,configuration);
byte[] bytes = JSON.toJSONString(configuration).getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);

NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 

Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, 
fromServiceAccount(configFileStream))
                .setApplicationName(APPLICATION_NAME)
                .build();


//    private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_APPDATA,DriveScopes.DRIVE,DriveScopes.DRIVE_METADATA,DriveScopes.DRIVE_READONLY,DriveScopes.DRIVE_METADATA_READONLY,DriveScopes.DRIVE_SCRIPTS);//Collections.singletonList(DriveScopes.DRIVE);
    private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
private static HttpRequestInitializer fromServiceAccount(InputStream configJsonFile) throws IOException {
        GoogleCredentials credentials = ServiceAccountCredentials.fromStream(configJsonFile).createScoped(SCOPES);
        return new HttpCredentialsAdapter(credentials);
    }

这里说明了 通过拿到配置的文件信息 创建一个 Drive ,我们操作后面都需要使用这个类去操作。这个我通过把配置文件的方式直接转成流的方式传进去了。

这里的 SCOPES 一定要设置你需要的授权范围,很重要

之前我说过我们可以直接使用读取json文件的方式的  

InputStream configFileStream =当前类.class.getResourceAsStream("/google-drive-config.json");
final NetHttpTransport HTTP_TRANSPORT =GoogleNetHttpTransport.newTrustedTransport();
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, fromServiceAccount(configFileStream))
                .setApplicationName(APPLICATION_NAME)
                .build();

只要把文件存放在resources 下面就行了 

 

第四步: 上传图片的过程:

 @PostMapping("/upload")
    public Mono<RestResponse> uploadGoogleDrive(
            @RequestParam("file") MultipartFile uploadFile){
File path = MultipartFileToFile.multipartFileToFile(uploadFile);
            googleDriveService.uploadFile(userInfo.getEmail()+"-"+type,file,UploadFileId);
            MultipartFileToFile.delteTempFile(file);
 public static File uploadFile(String fileName, java.io.File path,String UploadFileId) throws IOException {
        log.info("[uploadFile] google");
        File fileMetadata = new File();
        fileMetadata.setName(fileName+".jpg");
        fileMetadata.setParents(Collections.singletonList(UploadFileId));
        java.io.File filePath = new java.io.File(path,"");
        FileContent mediaContent = new FileContent("image/jpeg", filePath);
        File file = service.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();
        return file;
    }

上面的意思就是 ,我给上传的文件创建了一个临时文件,这是在缓冲区上的。程序关闭后 ,或者执行完后执行删除的操作。

最后我们通过拿到 Drive 的service 引用来执行上传的操作。

参数说明:

     fileName: 这个是上传文件的名称

     UploadFileId :表示文件夹是我通过 文件夹的Id ,你可以通过Drive的方法获取到,或者你直接 https://drive.google.com/drive 找你通过通过共享的文件夹点击 然后看URL 上面就有

   eg:   https://drive.google.com/drive/folders/1VtQOxEX7gYLrwzXZGhI6     然后 1VtQOxEX7gYLrwzXZGhI6 就是对应的文件夹ID了 。

 

最后应该就可以看到你的效果了。

 

可能出现的问题:

!!!!!如果你在使用的过程中出现了403 权限不足或者授权的问题,需要看看你的  SCOPES 是不是授权对了。

!!!!! 其它的应该没有了

 

这里只是简单的列举出来还有更多的API可以使用 

可以参考如下的官网API 文档:

https://developers.google.com/drive/api/v3/quickstart/java

这里采用的是Google Drive 服务账号的方式请求API,如有错误请体谅,麻烦指出 谢谢

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值