Google Drive API+SpringBoot 实现Doc转html

前言

Google Drive API支持上传文件并以HTML格式返回,后期解析相对容易,且导入还原度接近100%。

导出HTML效果:
1、HTML标签顺序基本与展现结果一致,只是行内的图片样式有些偏差(这点对结构化不成问题,去除CSS样式即可)。
2、图文混排有点坑,可能上下错位。但如果产品加入可拖动元素的交互,可减轻问题。
3、其它问题待发现。

一、OAuth授权

1、创建OAuth client
Google Console页面 进入你的project(没有就创建一个),然后创建一个credentials。这里选择OAuth client ID,使用场景是接口所以选了"Other"。

Googleapi-授权1.jpg

Googleapi-授权2.jpg

2、获取access token
放入项目/src/resources/credentials.json

{
  "installed": {
    "client_id": "自己申请的",
    "project_id": "my-project-19986-1",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "自己申请的",
    "redirect_uris": [
      "urn:ietf:wg:oauth:2.0:oob",
      "http://localhost"
    ]
  }
}

二、代码实现

1、Java Quickstart 加依赖和DriveQuickstart例子
验证鉴权和读取文件列表功能。pom.xml添加如下依赖:

 <!--Google Drive API3 -->
<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v3-rev110-1.23.0</version>
</dependency>

\color{red}{注意:官方文档例子,获取证书,每次都要手动鉴权。可以获取鉴权信息作为配置,后续每次直接使用}
1)、使用官方代码获取鉴权信息

获取鉴权信息.png

\color{red}{2)、新获取证书方式代码实现}
从“GoogleClientSecrets clientSecrets”:获取clientId、clientSecret
从“GoogleAuthorizationCodeFlow flow”:获取accessToken、refreshToken

private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
       // GoogleCredential.Builder
       return new GoogleCredential.Builder()
                .setClientSecrets(clientId, clientSecret)
                .setJsonFactory(JacksonFactory.getDefaultInstance()).setTransport(HTTP_TRANSPORT).build()
                .setAccessToken(accessToken).setRefreshToken(refreshToken);
}

2、文件上传 + 文件导出 验证csv文件上传和导出
例子是只读所以要修改DriveScopes
\color{red}{注意:修改DriveScopes后,要删除 tokens/StoredCredential}

/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);

3、上传word文档并导出html
注意设置各类型
fileMetadata.setMimeType:application/vnd.google-apps.document
FileContent.type:application/vnd.openxmlformats-officedocument.wordprocessingml.document
上传之后可以根据File ID验证仓库文件:替换“document/d/”之后内容
service.files().export.type:text/html

// 上传文件:以本地doc转html为例
File fileMetadata =new File();
fileMetadata.setMimeType("application/vnd.google-apps.document");
String name ="test";// 在此处修改文件名
java.io.File filePath =new java.io.File(String.format("/.../%s.doc", name));
FileContent mediaContent =new FileContent("application/vnd.openxmlformats-officedocument.wordprocessingml.document", filePath);
File file =service.files().create(fileMetadata, mediaContent).setFields("id").execute();
System.out.println("File ID: " + file.getId());
// 下载文件
OutputStream outputStream =new FileOutputStream(String.format("/.../%s.html", name));
service.files().export(file.getId(),"text/html").executeMediaAndDownloadTo(outputStream);

三、问题汇总

1、Insufficient Permission: Request had insufficient authentication scopes
导入的例子是只读,此时要上传或下载文件需要修改DriveScopes。

2、com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
修改DriveScopes后,需要删除 tokens/StoredCredential 并执行代码生成新的。

3、Export only supports Google Docs
包括上传文件后根据File ID 查看有格式问题等,都是MimeType相关类型错误或不匹配导致。
根据 Supported MIME types + ref-export-formats 找到匹配的类型。

4、如何删除上传到谷歌的文件来释放空间
https://drive.google.com/drive/u/0/quota

参考文档
鉴权:https://developers.google.com/identity/protocols/oauth2
Java Quickstart:https://developers.google.com/drive/api/v3/quickstart/java
文件上传:https://developers.google.com/drive/api/v3/manage-uploads#resumable
文件导出:https://developers.google.com/drive/api/v3/reference/files/export
帮助文档:https://www.jianshu.com/p/6abb4c421bc6

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 抽奖活动API 获取参与抽奖名单 分页获取参与抽奖名单 导出参与名单的报表模板 导入参与名单 内定中奖名单列表 获...
    kingsonCai阅读 2,641评论 1 1
  • 踏踏实实的行动记录起来,写下来的会更深刻。满满的感动,谢谢子祺的邀请,分享就是一份最好的建立彼此的连接和传递,美好...
    央金拉姆阅读 422评论 0 0
  • 曾经在我的一份简历中有过这么一句话“我是一个有毅力,认定目标就决不放弃的人”。但事实呢?好像不太真实。 大学期间,...
    蜗牛你飞啊阅读 273评论 0 2
  • 人生若只如初见,何事秋风悲画扇。 ——纳兰性德 想到昨晚写的《浪漫满屋》,自己十分不满...
    糖小唐的笨鱼阅读 481评论 0 0

友情链接更多精彩内容