使用java从Google Drive下载Google文档文件 [英] Download Google Docs file from Google Drive with java
问题描述
我试图从Google云端硬盘下载文件。通用文件(pdf,jpg)的下载没有任何问题。但我无法得到它下载谷歌文件。我得到一个没有类型和大小为0的空文件。你知道什么可能导致这种情况?
public InputStream下载(String id)抛出CloudServiceException {
尝试{
文件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);
$ / code $ / pre
解决方案问题实际上是在建立一个回应。 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()));
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);
}
}
解决方案 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()));
这篇关于使用java从Google Drive下载Google文档文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!