Visual FoxPro 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


LOCAL loRest
LOCAL lnSuccess
LOCAL loOauth2
LOCAL lnStatusCode
LOCAL loSbErrResponse
LOCAL loRespBodyStream

loRest = CreateObject('Chilkat_9_5_0.Rest')

*   Provide a previously obtained OAuth2 access token.
loOauth2 = CreateObject('Chilkat_9_5_0.OAuth2')
loOauth2.AccessToken = "OAUTH2_ACCESS_TOKEN"
loRest.SetAuthOAuth2(loOauth2)

lnSuccess = loRest.Connect("www.googleapis.com",443,1,1)
IF (lnSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loRest
    RELEASE loOauth2
    CANCEL
ENDIF

loRest.AddQueryParam("includeTeamDriveItems","true")
loRest.AddQueryParam("supportsTeamDrives","true")
loRest.AddQueryParam("alt","media")

*  First send the HTTP request.
lnSuccess = loRest.SendReqNoBody("GET","/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl")
IF (lnSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loRest
    RELEASE loOauth2
    CANCEL
ENDIF

*  Read the response header.  If the response status code is success, stream to the file.
*  Otherwise receive the error response text.
lnStatusCode = loRest.ReadResponseHeader()
IF (lnStatusCode < 0) THEN
    ? loRest.LastErrorText
    RELEASE loRest
    RELEASE loOauth2
    CANCEL
ENDIF

IF (lnStatusCode <> 200) THEN
    ? "Received error response code: " + STR(lnStatusCode)
    *  Read the error response body.
    loSbErrResponse = CreateObject('Chilkat_9_5_0.StringBuilder')
    lnSuccess = loRest.ReadRespSb(loSbErrResponse)
    IF (lnSuccess <> 1) THEN
        ? loRest.LastErrorText
        RELEASE loRest
        RELEASE loOauth2
        RELEASE loSbErrResponse
        CANCEL
    ENDIF

    ? "Error response:" + loSbErrResponse.GetAsString()
    RELEASE loRest
    RELEASE loOauth2
    RELEASE loSbErrResponse
    CANCEL
ENDIF

*  Stream the response body to the output file.
loRespBodyStream = CreateObject('Chilkat_9_5_0.Stream')
loRespBodyStream.SinkFile = "/someDirectory/penguins.jpg"
lnSuccess = loRest.ReadRespBodyStream(loRespBodyStream,1)
IF (lnSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loRest
    RELEASE loOauth2
    RELEASE loSbErrResponse
    RELEASE loRespBodyStream
    CANCEL
ENDIF

? "Example Completed."

RELEASE loRest
RELEASE loOauth2
RELEASE loSbErrResponse
RELEASE loRespBodyStream