是否可以为在 Google 云端硬盘中上传的私有(private)文件生成可下载链接?
我尝试使用文件 API 并生成了“webContent 链接”,但只有所有者和共享用户才能访问它。
(期望可以与任何人共享的公共(public)链接)
def file_info_drive(access_token, file_id):
headers = {'Authorization': 'Bearer ' + access_token, "content-type": "application/json"}
response = requests.get('https://www.googleapis.com/drive/v2/files/{file_id}', headers=headers)
response = response.json()
link = response['webContentLink']
return link
最佳答案
- 您想让任何人都使用
webContentLink
下载该文件。 - 您想要使用 Drive API v2。
- 您希望使用 Python 的“请求”模块来实现此目的。
- 您已经能够使用 Drive API 上传和下载文件。
如果我的理解是正确的,那么修改一下怎么样?
修改点:
- 为了让任何人都可以使用
webContentLink
下载该文件,需要公开共享该文件。- 在此修改后的脚本中,文件以
{'role': 'reader', 'type': 'anyone', 'withLink': True} 条件公开共享
。在这种情况下,知道 URL 的人就可以下载该文件。
- 在此修改后的脚本中,文件以
修改后的脚本:
当你的脚本修改后,它会变成如下。
def file_info_drive(access_token, file_id):
headers = {'Authorization': 'Bearer ' + access_token, "content-type": "application/json"}
# Using the following script, the file is shared publicly. By this, anyone can download the file.
payload = {'role': 'reader', 'type': 'anyone', 'withLink': True}
requests.post('https://www.googleapis.com/drive/v2/files/{file_id}/permissions', json=payload, headers=headers)
response = requests.get('https://www.googleapis.com/drive/v2/files/{file_id}', headers=headers)
response = response.json()
link = response['webContentLink']
return link
注意:
- 在本例中,使用 POST 方法。因此,如果范围发生错误,请将
https://www.googleapis.com/auth/drive
添加到范围。
引用:
如果我误解了您的问题并且这不是您想要的方向,我深表歉意。
关于python - 为 Google 云端硬盘中上传的私有(private)文件生成可下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318228/