gpt4 book ai didi

java - 使用 Google Drive API 获取文件大小

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:39 25 4
gpt4 key购买 nike

我正在尝试列出来自 Google 云端硬盘的文件及其适用于我的应用程序的大小,下面是我尝试获取大小的方法

File file = service.files().get(file.getId()).setFields("size").execute();
file.getSize()

我开始知道从这次调用中获得的大小不正确,因为谷歌驱动器仅填充除谷歌文档、工作表 Get size of file created on Google drive using Google drive api in android 之外的文件的文件大小。

我还尝试通过 http GET 来确定文件的大小webContentLink 并检查 Content-Length header ,如下所示

HttpURLConnection conn = null;
String url = "https://docs.google.com/a/document/d/1Gu7Q2Av2ZokZZyLjqBJHG7idE1dr35VE6rTuSii36_M/edit?usp=drivesdk";
try {
URL urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
System.out.println(conn.getContentLength());
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}

但在这种情况下,文件大小不正确,因为它非常大

有什么方法可以确定文件大小吗?

最佳答案

找到问题的解决方案。对于上传到谷歌驱动器的文件,可以通过调用 file.getSize() 确定文件大小。对于 Google 应用程序文件,例如文档、电子表格等,file.getSize() 将返回 null,因为它们不占用驱动器中的任何空间。因此,作为一种黑客方式,我将其导出为 pdf 并确定大小。下面是代码

try {
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("xyz")
.build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
service.files().export(fileId, "application/pdf")
.executeMediaAndDownloadTo(outputStream);
int fileSize = outputStream.toByteArray().length;
} catch (Exception ex) {

}

关于java - 使用 Google Drive API 获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com