2015-10-22 235 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

相关问题