【问题标题】:Download pdf and tif file from google drive in java在java中从谷歌驱动器下载pdf和tif文件
【发布时间】:2014-05-06 10:16:15
【问题描述】:

我正在使用以下代码使用 GDrive v2 api 从谷歌驱动器下载 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文件并打开文件。 我也想知道谷歌驱动器中的文件是否已经完全下载。

请帮帮我。

提前致谢。

【问题讨论】:

  • 你检查你的文件ID是否正确?
  • 如何查看文件ID?
  • 您是如何获得文件 ID 的?方法downloadFile是怎么调用的?
  • String fileID = request.getParameter("fileID"); System.out.println("文件 ID" + fileID);输入流是 = null; ServletOutputStream so = null;字节[] bt = null; is = driveaccess.downloadFile(serviceGoogleAPI, fileID);
  • 是的,我完全理解。您如何确认 fileID 实际上指向 Google 驱动器中的正确文件?

标签: java android pdf google-api google-drive-api


【解决方案1】:

您不必在 API 中选择导出选项,因为 pdf 文件仅在驱动器中可用,并且不会发生从 Google doc 格式到任何转换格式(如 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 创建一个文件。以下 sn-p 可能会有所帮助

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 文件。希望这对路过的人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-05
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多