Search code examples
pythongoogle-drive-apigoogle-picker

Google Picker and download the selected file


I have managed to integrate the google Picker. Now I have the FileId and the access_token. I need to download the selected file in my back end which is in Python. I have followed the documentation on google developers but If i use the python library then i have to authenticate the user again which is not suitable in my case. Please enlighten me if I can download the file with any format.

Thanks in advance.


Solution

  • This is a very simple sample script for downloading files using access token and file id without Google library. And this sample supposes files (images and videos) except for Google Docs, as you said. The flow is as follows.

    Flow :

    1. Retrieve filename and mimeType.
    2. Create filename from retrieved filename and mimeType. If the filename doesn't have the extension on Google Drive, this script adds the extension to the filename using mimeType and save it. If the filename has the extension on Google Drive, this script uses the original filename and save it.
    3. Download a file and save it as the created filename. If you want to save the file to the specific directory, please set it by yourself.

    Sample script :

    import mimetypes
    import os.path
    import requests
    accessToken = "### access token ###"
    fileId = "### file id ###"
    fileInf = requests.get(
        "https://www.googleapis.com/drive/v3/files/" + fileId,
        headers={"Authorization": "Bearer " + accessToken},
    )
    filename = fileInf.json()["name"]
    temp, ext = os.path.splitext(filename)
    filename = filename if ext != "" else filename + mimetypes.guess_extension(fileInf.json()["mimeType"])
    r = requests.get(
        "https://www.googleapis.com/drive/v3/files/" + fileId + "?alt=media",
        headers={"Authorization": "Bearer " + accessToken},
    )
    with open(filename, "wb") as f:
        f.write(r.content)
    

    If this was not helpful for you, I'm sorry.