Tcl Google Drive: Download a File (Stream to the Filesystem)

Back to Index

Downloads the content of a file by ID. (In this example the file id = 1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl) The file is streamed directly to the filesystem. Note: The alt=media query param must be used to download the file content (as opposed to the file metadata).

Documentation: https://developers.google.com/drive/v3/reference/files/get



load ./chilkat.dll

set rest [new_CkRest]

#   Provide a previously obtained OAuth2 access token.
set oauth2 [new_CkOAuth2]

CkOAuth2_put_AccessToken $oauth2 "OAUTH2_ACCESS_TOKEN"
CkRest_SetAuthOAuth2 $rest $oauth2

set success [CkRest_Connect $rest "www.googleapis.com" 443 1 1]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    exit
}

CkRest_AddQueryParam $rest "includeTeamDriveItems" "true"
CkRest_AddQueryParam $rest "supportsTeamDrives" "true"
CkRest_AddQueryParam $rest "alt" "media"

#  First send the HTTP request.
set success [CkRest_SendReqNoBody $rest "GET" "/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl"]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    exit
}

#  Read the response header.  If the response status code is success, stream to the file.
#  Otherwise receive the error response text.
set statusCode [CkRest_ReadResponseHeader $rest]
if {[expr $statusCode < 0]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    exit
}

if {[expr $statusCode != 200]} then {
    puts "Received error response code: $statusCode"
    #  Read the error response body.
    set sbErrResponse [new_CkStringBuilder]

    set success [CkRest_ReadRespSb $rest $sbErrResponse]
    if {[expr $success != 1]} then {
        puts [CkRest_lastErrorText $rest]
        delete_CkRest $rest
        delete_CkOAuth2 $oauth2
        delete_CkStringBuilder $sbErrResponse
        exit
    }

    puts "Error response:[CkStringBuilder_getAsString $sbErrResponse]"
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    delete_CkStringBuilder $sbErrResponse
    exit
}

#  Stream the response body to the output file.
set respBodyStream [new_CkStream]

CkStream_put_SinkFile $respBodyStream "/someDirectory/penguins.jpg"
set success [CkRest_ReadRespBodyStream $rest $respBodyStream 1]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    delete_CkStringBuilder $sbErrResponse
    delete_CkStream $respBodyStream
    exit
}

puts "Example Completed."

delete_CkRest $rest
delete_CkOAuth2 $oauth2
delete_CkStringBuilder $sbErrResponse
delete_CkStream $respBodyStream