1. Computing & Technology

Discuss in my forum

Preview HTTP Posted Data using Delphi and TWebBrowser

By , About.com Guide

Code submitted by Jason Penny.

OleVariantToMemoryStream

When you need to programmatically upload multiple files to an HTML form using the HTTP Post method - you can use the TWebBrowser Delphi control.

Before actually sending information you might need to preview the data to be posted. Use the OnBeforeNavigate2 event of the TWebBrowser control.

 procedure TPostForm.WebBrowser1BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool) ;
   function OleVariantToMemoryStream(OV: OleVariant): TMemoryStream;
   var
     Data: PByteArray;
     Size: integer;
   begin
     Result := TMemoryStream.Create;
     try
        Size := VarArrayHighBound (OV, 1) - VarArrayLowBound(OV, 1) + 1;
        Data := VarArrayLock(OV) ;
        try
          Result.Position := 0;
          Result.WriteBuffer(Data^, Size) ;
        finally
          VarArrayUnlock(OV) ;
        end;
     except
        Result.Free;
        Result := nil;
     end;
   end;
 var
   ms: TMemoryStream;
   ss: TStringStream;
 begin
   ss := TStringStream.Create('') ;
   try
     if Length(PostData) > 0 then
     begin
       ms := OleVariantToMemoryStream(PostData) ;
       ms.Position := 0;
       ss.CopyFrom(ms, ms.size) ;
       ss.Position := 0;
       ShowMessage('HEADER:' + Headers + #13#10#13#10 + ss.DataString) ;
     end;
   finally
     ss.Free;
   end;
 end;
 

Delphi tips navigator:
» How to Restore a Delphi Form from Minimized / Maximized state to the Previous State, Programmatically!
« Programmatically Executing HTTP POST

©2012 About.com. All rights reserved.

A part of The New York Times Company.