我使用下面的代码通过 GDrive v2 api 从 Google 云端硬盘下载 pdf 文件。
public InputStream downloadFile(Drive service, String fileId) {
try {
System.out.println("From Down load file file id" + fileId);
System.out.println("From Down load file file id" + service);
File file = service.files().get(fileId).execute();
String downloadUrl = file.getDownloadUrl();
if (downloadUrl != null && downloadUrl.length() > 0) {
HttpResponse resp = service.getRequestFactory()
.buildGetRequest(new GenericUrl(downloadUrl)).execute();
System.out.println("resp content: " + resp.getContent());
return resp.getContent();
} else {
// The file doesn't have any content stored on Drive.
return null;
}
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
}
当我打开下载的 pdf 文件时,收到警告,提示“文件格式已损坏或不受支持”。在谷歌开发者控制台中,他们提到使用以下行
String downloadUrl = file.getExportLinks().get("application/pdf");
但是当我使用上面的行时,我遇到了空指针异常。任何人都可以告诉我如何替换代码中的上述行来下载 pdf 文件并打开该文件。 我还想知道谷歌驱动器中的文件是否已完全下载。
请帮助我。
提前致谢。
最佳答案
您不必在 API 中选择导出选项,因为 pdf 文件仅在驱动器中可用,并且不会发生从 Google 文档格式到任何转换格式(如 pdf)的转换。这就是为什么您在获取导出链接时会得到 NPE
的原因。您可以直接通过API发出Http Get请求来下载文件,如下所示
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
您必须创建一个 FileOutputStream
而不是 ByteArrayOutputStream
才能使用 InputStream
创建文件。下面的代码 fragment 可能会有所帮助
OutputStream outputStream = new FileOutputStream(new File("/home/input.pdf"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
确保刷新 OutputStream
并在使用后关闭两个流。
注意:我在聊天中与 OP 讨论后得到了这个详细的答案。为了简单起见,OP 使用 ByteArrayOutputStream 而不是 FileOutputStream 来创建 pdf 文件。希望这可以帮助路过的人!
关于java - 在java中从Google Drive下载pdf和tif文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23491899/