GoogleDrive中上传文件,Java整合操作

GoogleDrive使用ServiceAccount的授权方式:(科学上网)

1.在Google Cloud中查看自己的项目: Dashboard -- My First Project -- Google Cloud console 没有的话新建项目。默认名称:My First Project

2. 创建ServiceAccount服务账号:

3. 添加私钥,可选用json格式,方便读取,可下载下来
4. 开启Google Drive Api,直接在搜索栏里搜索即可:点击ENABLE后显示API Enabled
5. 在云端硬盘中操作: Home - Google Drive 创建目录

1)其中的link是:
https://drive.google.com/drive/folders/17hvNdQUwd10cnD9Ur2JlxrybMuYBCpw0?usp=drive_link,
那么这里的17hvNdQUwd10cnD9Ur2JlxrybMuYBCpw0就是fileId,后面代码中也有体现:
2)而权限也是至关重要:点击这个文件夹的share,或者是点击右侧的Manage access:
3)其中share中我们要选择editor才可以上传文件:
至此,账号及权限问题我们都解决了。现在直接上源码:
1. maven管理依赖:

<!-- GoogleDrive 相关依赖包 -->
<!-- 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-rev197-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.34.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.23.0</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.35.0</version>
</dependency>

2. 代码如下:

// 一些 scope 权限

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

/**
* 校验认证权限
* @param configJsonFile
* @return
* @throws IOException
*/

private static HttpRequestInitializer fromServiceAccount(InputStream configJsonFile) throws IOException {

GoogleCredentials credentials = ServiceAccountCredentials.fromStream (configJsonFile).createScoped(SCOPES );

return new HttpCredentialsAdapter(credentials);
}

/**
* 根据后缀名获取文件类型
* @param suffix
* @return
*/
public static String findMineTypeBySuffix(String suffix) {

for (MineTypeOnGoogleDriveEnum type : MineTypeOnGoogleDriveEnum.values ()) {

if (type.getSuffix().equalsIgnoreCase(suffix)) {

return type.getFileType();
}
}

return "Unknown mine type";
}

/**
* GoogleDrive 的后缀名 === mineType ,枚举类
*/

@Getter
@AllArgsConstructor
public enum MineTypeOnGoogleDriveEnum {

TXT ("txt", "text/plain"),

JPG ("jpg", "image/jpeg"),

JPEG ("jpeg", "image/jpeg"),

PNG ("png", "image/png"),

PDF ("pdf", "application/pdf"),

DOC ("doc", "application/msword"),

DOCX ("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),

XLS ("xls", "application/vnd.ms-excel"),

XLSX ("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),

PPT ("ppt", "application/vnd.ms-powerpoint"),

PPTX ("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"),

ZIP ("zip", "application/zip");

private final String suffix;

private final String fileType;
}

Psvm:

public static void main(String[] args) {

try {

// 0. 构建 http 传输
NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport ();

// 1. 根据 json 配置文件,构建输入流
InputStream configFileStream = GoogleDriveServiceImpl.class.getResourceAsStream("/google-drive-config.json");

// 2. 创建 Drive 实例
Drive drive = new Drive.Builder(httpTransport, new GsonFactory(), fromServiceAccount (configFileStream))
.setApplicationName("Application-Name")
.build();

// 3. 指定上传文件的路径
java.io.File filePath = new java.io.File("/22.txt");

String suffix = FileUtil.getSuffix (filePath);

// 4. 构建文件元数据:文件名,父目录,文件的 mineType
File fileMetadata = new File();

fileMetadata.setName("add."+ suffix);

fileMetadata.setParents(Collections.singletonList ("17hvNdQUwd10cnD9Ur2JlxrybMuYBCpw0"));

String mineType = findMineTypeBySuffix (suffix);

FileContent mediaContent = new FileContent(mineType, filePath);

// 5. 上传文件
File uploadedFile = drive.files().create(fileMetadata, mediaContent)
.setFields("id,name")
.execute();

System.out .println("FileId: " + uploadedFile.getId());

System.out .println("FileName: " + uploadedFile.getName());
} catch (IOException | GeneralSecurityException e) {

throw new RuntimeException(e);
}
}

最后,FileId就是文件id,那么文件的链接就是https://drive.google.com/file/d/s%/view中的s%替换即可。

3. 测试:

尤为重要的是看是否可以ping通:googleapis.com。如果可以那么就能上传成功。若不可以也能上传成功,可以私信我,欢迎交流一下。

相关推荐
·云扬·1 分钟前
使用pt-archiver实现MySQL数据归档与清理的完整实践
数据库·mysql
黄焖鸡能干四碗4 分钟前
信息安全管理制度(Word)
大数据·数据库·人工智能·智慧城市·规格说明书
zhangyifang_0099 分钟前
PostgreSQL一些概念特性
数据库·postgresql
2401_8414956414 分钟前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
weixin_466815 分钟前
安装Zabbix7
数据库·mysql·zabbix
little_xianzhong15 分钟前
三个常听到的消息/中间件MQTT RabbitMQ Kafka
java·笔记·中间件·消息队列
论迹23 分钟前
【Spring Cloud 微服务】-- 服务拆分原则
java·spring cloud·微服务
汤姆yu26 分钟前
基于springboot的民间救援队救助系统
java·spring boot·后端·救援队
数据库生产实战27 分钟前
Oracle 19C实测:重命名分区表后又重命名分区索引,分区索引会失效吗?DBA必看避坑指南!
数据库·oracle·dba
闭着眼睛学算法28 分钟前
【双机位A卷】华为OD笔试之【哈希表】双机位A-采购订单【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·华为od·散列表