简体   繁体   中英

Download Google Docs file from Google Drive with java

I am trying to download a file from Google Drive. Download of a common file (pdf, jpg) went without any problem. 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?

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.

Edit: Here is my working version. I removed the set size so that it downloads those 0 sized files.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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