Unicode C++ 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


#include <CkRestW.h>
#include <CkOAuth2W.h>
#include <CkStringBuilderW.h>
#include <CkStreamW.h>

void ChilkatSample(void)
    {
    CkRestW rest;
    bool success;

    //   Provide a previously obtained OAuth2 access token.
    CkOAuth2W oauth2;
    oauth2.put_AccessToken(L"OAUTH2_ACCESS_TOKEN");
    rest.SetAuthOAuth2(oauth2);

    success = rest.Connect(L"www.googleapis.com",443,true,true);
    if (success != true) {
        wprintf(L"%s\n",rest.lastErrorText());
        return;
    }

    rest.AddQueryParam(L"includeTeamDriveItems",L"true");
    rest.AddQueryParam(L"supportsTeamDrives",L"true");
    rest.AddQueryParam(L"alt",L"media");

    //  First send the HTTP request.
    success = rest.SendReqNoBody(L"GET",L"/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl");
    if (success != true) {
        wprintf(L"%s\n",rest.lastErrorText());
        return;
    }

    //  Read the response header.  If the response status code is success, stream to the file.
    //  Otherwise receive the error response text.
    int statusCode = rest.ReadResponseHeader();
    if (statusCode < 0) {
        wprintf(L"%s\n",rest.lastErrorText());
        return;
    }

    if (statusCode != 200) {
        wprintf(L"Received error response code: %d\n",statusCode);
        //  Read the error response body.
        CkStringBuilderW sbErrResponse;
        success = rest.ReadRespSb(sbErrResponse);
        if (success != true) {
            wprintf(L"%s\n",rest.lastErrorText());
            return;
        }

        wprintf(L"Error response:%s\n",sbErrResponse.getAsString());
        return;
    }

    //  Stream the response body to the output file.
    CkStreamW respBodyStream;
    respBodyStream.put_SinkFile(L"/someDirectory/penguins.jpg");
    success = rest.ReadRespBodyStream(respBodyStream,true);
    if (success != true) {
        wprintf(L"%s\n",rest.lastErrorText());
        return;
    }

    wprintf(L"Example Completed.\n");
    }