Home > Mobile >  Python: how to get a direct Google docs url after uploading to Google drive?
Python: how to get a direct Google docs url after uploading to Google drive?

Time:10-31

I want to upload a text file .txt to Google drive and be able to get a direct link where I can edit it directly, so I've written this method

def upload(self, file_name, filepath, folder_id, file_id=None, mimeType='text/plain'):

media = MediaFileUpload(
    filepath, mimetype=mimeType, resumable=True)
try:
    if file_id is None:
        file_metadata = {"name": file_name,
                            "parents": [folder_id]
                            }
        file = self.drive.files().create(
            body=file_metadata,
            media_body=media, fields='id').execute()
        file_id = file.get('id')
    else:
        file_metadata = {"name": file_name}
        self.drive.files().update(
            body=file_metadata, removeParents='root',
            media_body=media, fileId=file_id).execute()
    url = 'https://drive.google.com/open?id='   file_id

    return file_name, file_id, url

It's returning a URL that takes you to a document viewer and then you have to click "open with Google docs"

enter image description here

But I want to get a direct link that opens with Google docs, but the URL of google docs is totally different than what I see in google drive.

Is it possible to get a direct Url to google docs after uploading a file to Google drive?

CodePudding user response:

The file you uploading the file as mimeType='text/plain' this is not a Google Drive mimetype. There is a list of mimetypes that are supported.

To covert your .txt file to a google docs file you would need to supply the mimetype to covert it to in the file metadata. You are not supplying a mimetype in the metadata so the file is not being coverted.

file_metadata = {
        "name": file_name,
        "parents": [folder_id]
        'mimeType': 'application/vnd.google-apps.document'
    }

Once converted the file should then open in Google docs.

  • Related