2015-10-22 97 views
2

我試圖從Google Drive下載文件。通用文件(pdf,jpg)的下載沒有任何問題。但我無法得到它下載谷歌文件。我得到一個沒有類型和大小爲0的空文件。你知道什麼可能會導致這種情況嗎?使用java從Google Drive下載Google文檔文件

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); 
    } 
} 

回答

0

所以這個問題實際上在響應建設。 Google文件大小爲0,Google媒體類型無法識別,導致此文件損壞。

編輯:這是我的工作版本。我刪除了設置大小,以便下載這些大小爲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())); 
+0

那麼如何解決它? – Nakilon

0

你可以試試這個:

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(); 
+0

感謝您的意見。問題依然存在。我試過,如果出口鏈接工作,並且它當我手動使用它。 – Januson

0

試試這個:

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; 
    } 

好運

+0

感謝您的建議。 Google文件文件沒有downloadUrl。我可以得到工作exportLink,但我不能從代碼下載它。 – Januson

+0

如果你有ID(這是一個字符串,如'UW2ablahblaghblahNy00Ums0B1mQ'),這有什麼關係嗎? – seanpj

+0

我會得到ID(字符串),然後在這個[page(Try It!)](https://developers.google.com/drive/v2/reference/files/list)的底部播放它,或者[這裏](https://developers.google.com/drive/v2/reference/files/get)。 – seanpj

相關問題