简体   繁体   English

使用 java 从 Google Drive 下载 Google Docs 文件

[英]Download Google Docs file from Google Drive with java

I am trying to download a file from Google Drive.我正在尝试从 Google Drive 下载文件。 Download of a common file (pdf, jpg) went without any problem.下载通用文件(pdf、jpg)没有任何问题。 But I can't get it to download Google files.但我无法下载谷歌文件。 I am getting an empty file without type and with size 0. Do you have any idea of what might cause this?我得到一个没有类型且大小为 0 的空文件。你知道是什么原因造成的吗?

public InputStream download(String id) throws CloudServiceException {
    try {
        File file = service.files()
                .get(id)
                .execute();
        String link = file.getExportLinks().get("application/pdf");
        HttpResponse resp = service.getRequestFactory()
                .buildGetRequest(
                        new GenericUrl(link))
                .execute();
        return resp.getContent();
    } catch (HttpResponseException e) {
        throw CloudServiceExceptionTransformer.transform(e, e.getStatusCode());
    } catch(IOException ex) {
        throw new InternalException(ex);
    }
}

You need to use Export method for downloading google docs or any google files您需要使用导出方法来下载谷歌文档或任何谷歌文件

String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
    .executeMediaAndDownloadTo(outputStream);

You can try this:你可以试试这个:

URL url = new URL("http://www.gaertner-servatius.de/images/sinnfrage/kapitel-2/spacetime.gif");
InputStream inStream = url.openStream();
Files.copy(inStream, Paths.get("foobar.gif"), StandardCopyOption.REPLACE_EXISTING);
inStream.close();

Try this:尝试这个:

 com.google.api.services.drive.Drive service;
 static InputStream download(String id)  {
   if (service != null && id != null) try {
     com.google.api.services.drive.model.File gFl =
        service.files().get(id).setFields("downloadUrl").execute();
     if (gFl != null){
       return service.getRequestFactory()
          .buildGetRequest(new GenericUrl(gFl.getDownloadUrl())).execute().getContent());
      }
    } catch (Exception e) { e.printStackTrace(); }
    return null;
  }

Good Luck祝你好运

So the problem was in fact in building of a response.所以问题实际上在于建立响应。 Google files have a size 0 and google media type was not recognized which resulted in this broken file. Google 文件的大小为 0,并且无法识别 Google 媒体类型,这导致此文件损坏。

Edit: Here is my working version.编辑:这是我的工作版本。 I removed the set size so that it downloads those 0 sized files.我删除了设置大小,以便它下载那些 0 大小的文件。

   ResponseEntity.BodyBuilder builder = ResponseEntity.status(HttpStatus.OK)
            .header(HttpHeaders.CONTENT_DISPOSITION, encoding)
            .contentType(MediaType.parseMediaType(resource.getMimeType()));
    return builder.body(new InputStreamResource(resource.getContent()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM