Delphi DLL 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


var
rest: HCkRest;
success: Boolean;
oauth2: HCkOAuth2;
statusCode: Integer;
sbErrResponse: HCkStringBuilder;
respBodyStream: HCkStream;

begin
rest := CkRest_Create();

//   Provide a previously obtained OAuth2 access token.
oauth2 := CkOAuth2_Create();
CkOAuth2_putAccessToken(oauth2,'OAUTH2_ACCESS_TOKEN');
CkRest_SetAuthOAuth2(rest,oauth2);

success := CkRest_Connect(rest,'www.googleapis.com',443,True,True);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;

CkRest_AddQueryParam(rest,'includeTeamDriveItems','true');
CkRest_AddQueryParam(rest,'supportsTeamDrives','true');
CkRest_AddQueryParam(rest,'alt','media');

//  First send the HTTP request.
success := CkRest_SendReqNoBody(rest,'GET','/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl');
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
statusCode := CkRest_ReadResponseHeader(rest);
if (statusCode < 0) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;
if (statusCode <> 200) then
  begin
    Memo1.Lines.Add('Received error response code: ' + IntToStr(statusCode));
    //  Read the error response body.
    sbErrResponse := CkStringBuilder_Create();
    success := CkRest_ReadRespSb(rest,sbErrResponse);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkRest__lastErrorText(rest));
        Exit;
      end;
    Memo1.Lines.Add('Error response:' + CkStringBuilder__getAsString(sbErrResponse));
    Exit;
  end;
//  Stream the response body to the output file.
respBodyStream := CkStream_Create();
CkStream_putSinkFile(respBodyStream,'/someDirectory/penguins.jpg');
success := CkRest_ReadRespBodyStream(rest,respBodyStream,True);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;

Memo1.Lines.Add('Example Completed.');

CkRest_Dispose(rest);
CkOAuth2_Dispose(oauth2);
    CkStringBuilder_Dispose(sbErrResponse);
CkStream_Dispose(respBodyStream);