【问题标题】:Generating a downloadable link for a private file uploaded in the Google drive为上传到 Google 云端硬盘中的私人文件生成可下载链接
【发布时间】:2019-10-10 08:09:34
【问题描述】:

是否可以为上传到谷歌驱动器中的私人文件生成可下载链接?

我已尝试使用文件 API 并生成了“webContent Link”,但只有所有者和共享用户才能访问它。

(期待一个可以与任何人共享的公共链接)

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

【问题讨论】:

    标签: python file google-drive-api drive


    【解决方案1】:
    • 您想让任何人使用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 添加到作用域。

    参考:

    如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

    【讨论】:

    • 如果我们通过更新权限来这样做,驱动器中的文件会公开吗?
    • @kkr 感谢您的回复。在上面修改的脚本中,只有文件 ID 的文件是公开共享的。这样,任何人都可以以只读方式打开该文件。而且,只有知道URL的用户才能访问,这种情况下,一般的搜索引擎都无法搜索到该文件。
    • 非常感谢您的回复和详细的描述@tanaike
    • @kkr 欢迎。如果我提出的脚本对您的目标没有用处,我深表歉意。
    • 不,这是我的预期。感谢您的帮助。
    猜你喜欢
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2016-08-09
    • 2016-09-04
    相关资源
    最近更新 更多