我正在尝试使用Slides API在Google幻灯片演示文稿中插入图片(PNG)。为此,我首先将图像上传到用户的云端硬盘,获取URL,然后通过正确的请求将其传递到Slide API,然后删除图像文件。
几周前曾经使用的方法:
image_url = '%s&access_token=%s' % (
drive_service.files().get_media(fileId=image_file_id).uri,
creds.token)
但是,已经出现changes to the Drive API,因此以这种方式构造的URL不再起作用。
我在弄清楚要在此处使用的新正确URL时遇到困难。根据描述更改的文档的选项为:
我使用看起来像这样的代码来获取这些链接:
upload = drive_service.files().create(
body={'name': 'My Image File'},
media_body=media_body,
fields='webContentLink, id, webViewLink').execute()
image_url = upload.get('webContentLink')
我已经尝试过#1和#2并收到以下错误:
"Invalid requests[0].createImage: The provided image is in an unsupported format."
我已确认能够从#1和#2中生成的URL下载/查看图像。我没有尝试#3,因为我没有尝试导出为其他格式。
找出正确的URL以使用的最佳方法是什么?
对于以上流程,python的示例脚本如下。请设置uploadFilename
,presentation_id
和pageObjectId
的变量>
uploadFilename = './sample.png' # Please set the filename with the path.
presentation_id = '###' # Please set the Google Slides ID.
pageObjectId = '###' # Please set the page ID of the Slides.
drive = build('drive', 'v3', credentials=creds)
slides = build('slides', 'v1', credentials=creds)
# 1. Upload a PNG file from local PC
file_metadata = {'name': uploadFilename}
media = MediaFileUpload(uploadFilename, mimetype='image/png')
upload = drive.files().create(body=file_metadata, media_body=media, fields='webContentLink, id, webViewLink').execute()
fileId = upload.get('id')
url = upload.get('webContentLink')
# 2. Share publicly the uploaded PNG file by creating permissions.
drive.permissions().create(fileId=fileId, body={'type': 'anyone', 'role': 'reader'}).execute()
# 3. Insert the PNG file to the Slides.
body = {
"requests": [
{
"createImage": {
"url": url,
"elementProperties": {
"pageObjectId": pageObjectId
}
}
}
]
}
slides.presentations().batchUpdate(presentationId=presentation_id, body=body).execute()
# 4. Delete the permissions. By this, the shared PNG file is closed.
drive.permissions().delete(fileId=fileId, permissionId='anyoneWithLink').execute()
注意:
我以为从您的脚本中可以将google-api-python-client与python一起使用。因此,我为python提出了示例脚本。