Unable to get thumbnail using Google Drive API

筅森魡賤 提交于 2019-11-28 19:46:00
Kalyan Reddy

I've posted this answer in a related question but it should be applicable here as well. We've recently made a change to fix this issue. Please try your code again and see if you are still getting this error. I was able to run the following code to successfully download a thumbnail of my Google Document.

# Get oauth credentials
...
# Authorize an http object
http = httplib2.Http()
http = credentials.authorize(http)

drive_service = build('drive', 'v2', http=http)

# Google Document type ID
docId = '1ns9x5BMIZAeUR-eXerqgpaHBBGkl_-_KCVpVoV5opn8'
files = drive_service.files().get(fileId=docId).execute()

thumbnailLink = files['thumbnailLink']
print 'Downloading thumbnail at: ', thumbnailLink
response, content = http.request(thumbnailLink)
print response.status

with open('thumbnail.jpg', 'wb') as f:
  f.write(content)

I had to do the same. Here is what worked for me:

final File file = drive.files().get(fileId).execute();
final String thumbnailLink = file.getThumbnailLink();

HttpRequest request = drive.getRequestFactory().buildGetRequest( new GenericUrl( thumbnailLink ) );
HttpResponse response = request.execute();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
response.download(byteArrayOutputStream);
InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

for the thumbnail link you can create with

https://drive.google.com/thumbnail?id={YOUR_IMAGE_FILE_ID}

By default that will return thumbnail of 220 px(max-width-220px max-height-220px, keeping the aspect ratio)

there are more parameters you can send with the link such as width, height Then we need to use 'sz' querystring https://drive.google.com/thumbnail?sz=w100-h100&id={YOUR_IMAGE_FILE_ID}

here sz=w100-h100 means height 100px and width 100px. you can pass anyone of them too. If you are sending both height and width then have to be sure about those values whether it is maintaining the original aspect ratio of the image.

Update: Update to the discussion of the request fields.

As far as I can tell, there is literally no good documentation on the solution for this. However, with the help of a co-worker and the REST API operation, I've gotten the solution.

To get valid thumbnailLink values using the Drive Java Client Library, you have to modify your query. Since you're doing a custom field request you have to be sure to add the other fields you want as well. Here is how I've gotten it to work:

Drive.Files.List request = yourGoogleDriveService.files()
                    .list()
                    .setFields("files/thumbnailLink, files/name, files/mimeType, files/id")
                    .setQ("Your file param and/or mime query");

FileList files = request.execute();
files.getFiles();  //Each File in the collection will have a valid thumbnailLink

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!