Delphi ActiveX 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: TChilkatRest;
success: Integer;
oauth2: TChilkatOAuth2;
statusCode: Integer;
sbErrResponse: TChilkatStringBuilder;
respBodyStream: TChilkatStream;

begin
rest := TChilkatRest.Create(Self);

//   Provide a previously obtained OAuth2 access token.
oauth2 := TChilkatOAuth2.Create(Self);
oauth2.AccessToken := 'OAUTH2_ACCESS_TOKEN';
rest.SetAuthOAuth2(oauth2.ControlInterface);

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

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

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

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
statusCode := rest.ReadResponseHeader();
if (statusCode < 0) then
  begin
    Memo1.Lines.Add(rest.LastErrorText);
    Exit;
  end;
if (statusCode <> 200) then
  begin
    Memo1.Lines.Add('Received error response code: ' + IntToStr(statusCode));
    //  Read the error response body.
    sbErrResponse := TChilkatStringBuilder.Create(Self);
    success := rest.ReadRespSb(sbErrResponse.ControlInterface);
    if (success <> 1) then
      begin
        Memo1.Lines.Add(rest.LastErrorText);
        Exit;
      end;
    Memo1.Lines.Add('Error response:' + sbErrResponse.GetAsString());
    Exit;
  end;
//  Stream the response body to the output file.
respBodyStream := TChilkatStream.Create(Self);
respBodyStream.SinkFile := '/someDirectory/penguins.jpg';
success := rest.ReadRespBodyStream(respBodyStream.ControlInterface,1);
if (success <> 1) then
  begin
    Memo1.Lines.Add(rest.LastErrorText);
    Exit;
  end;

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