unit uHTTPRequests2;

interface

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP,IdException,XMLIntf, XMLDoc,


  HTTPApp,
  IdMultipartFormData, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
  FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB,
  FireDAC.Comp.Client, System.IOUtils, System.Types,System.JSON,uCreateUniqueName,
  System.NetEncoding,

  //MyUnits

  uHTTP_ConnectionParams, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack;// IdSSL, IdSSLOpenSSL

type
  THTTPRequests2 = class(TDataModule)
  private



    { Private declarations }
  public
    { Public declarations }

    constructor Create(Aowner:TComponent); override;

    procedure IsFileOnServer( AFileName:string; AdirOnServer: string; var AMyServerResponse: string);
    function IsHTTPConnectionOk(var Error:string; var ResponseText:string ):boolean;

    {Sending One File to Server and Putting to some Dir;
    dirOnServer is dir on Server to Put File relatively to HTTPServer.exe}
    procedure SendOneFile(Filepath:string; dirOnServer:string; var StandartServerResponse:string; var MyServerResponse:string); overload;

    procedure SendOneFile(Filepath:string; dirOnServer:string; FileNameOnServer:string); overload;


    {Sending many files and putting them to dirOnSerer
    dirOnServer is dir on Server to Put File relatively to HTTPServer.exe}
    procedure SendManyFiles(FilepathesSL:TStringList; dirOnServer: string);

      {Sending many files and putting them to dirOnSerer
    dirOnServer is dir on Server to Put File relatively to HTTPServer.exe

    dirOnClient is the dir where chunks are
    }
    procedure SendManyFiles2(AbsDirOnClient, AbsDirOnServer: string);


    {Gathering and Sending chunks info on Server in String - doesn't worl well}
    procedure SendChunksInfo(AChunksDir, AChunksDirOnServer: string;AFileSize:int64);


    {Gathering and Sending chunks info on Server in File}
    procedure SendChunksInfoInFile(AChunksDir, AchunksDirOnServer: string; AFileSize: int64;ChunksInfoFileName:string);

    { this method will read ChunksInfo.txt on Server in dirOnServer
      and will check if all chunks are on Server

    }
    procedure CheckChunksIntegrity(AdirOnServer:string; var AMyServerResponse:string;AChunksInfoFileName:string);


    {creates dir on Server Relatively to HTTPServer.exe}
    procedure CreateDirOnServer(dir:string;MyServerResponse:string);

    procedure CreateCurrentDayDirOnServer;
    procedure CreateCurrentDayDirThumbsOnServer;
    procedure CreateTempFolderForFileChunks(Filename: string);


    procedure DeleteDirOnServer(dir: string;MyServerResponse:string);
    procedure DeleteTempFolderForFileChunks(Filename: string);

    {Delete File On Server}
    procedure DeleteFileOnServer(AFilePath, AMyServerResponse: string);

    procedure GatherFileFromChunks(AChunksDir:string; AOutPutDir:string; AOutPutFileName:string);
    procedure SendPostParamsForTest;





  end;

var
  HTTPRequests2: THTTPRequests2;

implementation


uses uVisualFrame;

var VisualFrame_HTTP_UnitVar:TVisualFrame_HTTP;

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}




procedure THTTPRequests2.
CheckChunksIntegrity(AdirOnServer:string; var AMyServerResponse:string;AChunksInfoFileName:string);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;




                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/checkChunksIntegrity';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');
                    PostData.AddFormField('dirOnServer', AdirOnServer);
                    PostData.AddFormField('ChunksInfoFileName', AChunksInfoFileName);



                  AMyServerResponse:=
                  idHTTP.Post(HTTPServerToRequest+'/checkChunksIntegrity', PostData);

                  if AMyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+AMyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;



procedure THTTPRequests2.IsFileOnServer(
AFileName:string;
AdirOnServer:string;
var AMyServerResponse:string);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;




                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/isfileonserver';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');
                    PostData.AddFormField('dirOnServer', AdirOnServer);
                    PostData.AddFormField('FileName', AFileName);



                  AMyServerResponse:=
                  idHTTP.Post(HTTPServerToRequest+'/isfileonserver', PostData);

                  if AMyServerResponse<>'ok' then
                  raise Exception.Create('Server Response '+AMyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;



constructor THTTPRequests2.Create(Aowner: TComponent);
begin
  inherited;

  if (Aowner is TVisualFrame_HTTP) then
  VisualFrame_HTTP_UnitVar:=(Aowner as TVisualFrame_HTTP);

end;

//---------------------------------------------------------------------------------

{Checking if HTTPServer Connection Ok}
function THTTPRequests2.IsHTTPConnectionOk(var Error, ResponseText: string): boolean;
begin

with VisualFrame_HTTP_UnitVar do begin


Result:=false;

    try

          IdHTTP.Get(HTTPServerToRequest+'/testConnection'); // //for example like http://localhost:40000

          if IdHTTP.ResponseCode=200 then// ResponseText='HTTP/1.1 200 OK' then
          Result:=true; // <<<< If Succeded

          //Also lets write Response Text
           ResponseText:=IdHTTP.ResponseText;


    except

    on E:Exception do

      begin
      ResponseText:=IdHTTP.ResponseText;

      raise Exception.Create('Server Connection Error '+ E.ClassName + 'error'+E.Message);
      //ShowMessage(E.ClassName + 'error'+E.Message );
      end;


    end;


end;


end;





//------------------------------------------------------------------


procedure THTTPRequests2.SendOneFile(
Filepath:string; dirOnServer: string; var StandartServerResponse:string; var MyServerResponse:string );

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;



                  if FilePath='' then Exit;


                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/sendfile';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');

                    PostData.AddFormField('dirOnServer', dirOnServer);

                    PostData.AddFile('attach', FilePath, 'application/x-rar-compressed');
                  //
                  //  PostData.AddFormField('action', 'post');



                  MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/sendfile', PostData);

                   if MyServerResponse<>'ok' then
                   raise Exception.Create('Server Response '+MyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                     StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;



procedure THTTPRequests2.SendOneFile(
Filepath:string; dirOnServer: string; FileNameOnServer:string  );

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;
  MyServerResponse:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;



                  if FilePath='' then Exit;


                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/sendfile';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');

                    PostData.AddFormField('dirOnServer', dirOnServer);
                    PostData.AddFormField('FileNameOnServer',FileNameOnServer);


                    PostData.AddFile('attach', FilePath, 'application/x-rar-compressed');
                  //
                  //  PostData.AddFormField('action', 'post');



                  MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/sendfile', PostData);

                   if MyServerResponse<>'ok' then
                   raise Exception.Create('Server Response '+MyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;



//--------------------------------------------------------------------



procedure THTTPRequests2.SendManyFiles(FilepathesSL:TStringList; dirOnServer: string);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  StandartServerResponse:string;
  MyServerResponse:string;
  i: integer;



begin

    with VisualFrame_HTTP_UnitVar do begin


    if not IsHTTPConnectionOk(Error,StandartServerResponse) then Exit;

       // Sending files here
      for i := 0 to FilepathesSL.Count-1  do
        begin

        MyServerResponse:='';
        StandartServerResponse:='';

        SendOneFile(FilepathesSL[i],dirOnServer,StandartServerResponse,MyServerResponse);

        if StandartServerResponse<>'HTTP/1.1 200 OK' then Exit;
        if MyServerResponse<>'ok' then Exit;

        end;






    end;


end;
//------------------------------------------------

procedure THTTPRequests2.SendManyFiles2(AbsDirOnClient:string; AbsDirOnServer: string);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  StandartServerResponse:string;
  MyServerResponse:string;
  i: integer;

  FilesSDA:TStringDynArray;
  AppPath: string;


begin


  //------------1 GAthering chunk files from dir on Client

   FilesSDA:=TDirectory.GetFiles(AbsDirOnClient);



    with VisualFrame_HTTP_UnitVar do begin


    if not IsHTTPConnectionOk(Error,StandartServerResponse) then Exit;


     for i := 0 to High(FilesSDA) do


        begin

        MyServerResponse:='';
        StandartServerResponse:='';

        SendOneFile(FilesSDA[i],AbsDirOnServer,StandartServerResponse,MyServerResponse);

        end;






    end;


end;


procedure THTTPRequests2.SendChunksInfo(AChunksDir:string; AchunksDirOnServer:string;AFileSize:int64);

var ChunksSDA:TStringDynArray;

    JsonObject:TJsonObject;
    NumberOfChunksAtAll: Integer;
    i: Integer;
    Filename:string;

    CurrentChunkNumber:string;
    ChunksInfoString: string;


    Error:string;
  ResponseText:string;
  PostData: TIdMultiPartFormDataStream;

begin

//-------------1 Gather info about chunks

ChunksSDA:=TDirectory.GetFiles(AChunksDir);
NumberOfChunksAtAll:=Length(ChunksSDA);
JSONObject:=TJSONObject.Create;

JSONObject.AddPair( (TJSONPair.Create('ChunksNumber',NumberOfChunksAtAll.ToString )) );
JSONObject.AddPair( (TJSONPair.Create('FileSize',AFileSize.ToString )) );

for i := 0 to High(ChunksSDA) do

begin
Filename:=ExtractFileName(ChunksSDA[i]);
if not Filename.Contains('chunk')  then Continue;  // All filenames should contain chunk word

CurrentChunkNumber:=
TCreateUniqueName.GetParamValueFromFileName(Filename,'chunk');

JSONObject.AddPair( (TJSONPair.Create(Filename,CurrentChunkNumber )) );

end;




ChunksInfoString:=JSONObject.ToString;

//TFile.WriteAllText('ChunksInfo.txt',ChunksInfoString);


//-------------2 Sending


   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/SendChunksInfo'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('ChunksInfoString', ChunksInfoString);
                PostData.AddFormField('AchunksDirOnServer', AchunksDirOnServer);

              //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
              //  PostData.AddFormField('action', 'post');

                idHTTP.Post(HTTPServerToRequest+'/SendChunksInfo', PostData);

                Application.ProcessMessages;
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;



end;



procedure THTTPRequests2.
SendChunksInfoInFile(AChunksDir:string; AchunksDirOnServer:string;AFileSize:int64; ChunksInfoFileName:string);

var ChunksSDA:TStringDynArray;

    JsonObject:TJsonObject;
    NumberOfChunksAtAll: Integer;
    i: Integer;
    TempFilename:string;

    CurrentChunkNumber:string;
    ChunksInfoString: string;

    ChunksInfoPath:string;

    Error:string;
    ResponseText:string;
    PostData: TIdMultiPartFormDataStream;

    MyServerResponse:string;

begin

//-------------1 Gather info about chunks

ChunksSDA:=TDirectory.GetFiles(AChunksDir);
NumberOfChunksAtAll:=Length(ChunksSDA);
JSONObject:=TJSONObject.Create;

JSONObject.AddPair( (TJSONPair.Create('ChunksNumber',NumberOfChunksAtAll.ToString )) );
JSONObject.AddPair( (TJSONPair.Create('FileSize',AFileSize.ToString )) );

for i := 0 to High(ChunksSDA) do

begin
TempFilename:=ExtractFileName(ChunksSDA[i]);
if not TempFilename.Contains('chunk')  then Continue;  // All filenames should contain chunk word

CurrentChunkNumber:=
TCreateUniqueName.GetParamValueFromFileName(TempFilename,'chunk');  // No errror handling here - could be troubles

JSONObject.AddPair( (TJSONPair.Create(TempFilename,CurrentChunkNumber )) );

end;




ChunksInfoString:=JSONObject.ToString;

ChunksInfoPath:=AChunksDir+'\'+ChunksInfoFileName;//'ChunksInfo.txt';

TFile.WriteAllText(ChunksInfoPath,ChunksInfoString);


//-------------2 Sending


   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/SendChunksInfo'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

              //  PostData.AddFormField('ChunksInfoString', ChunksInfoString);
                PostData.AddFormField('AchunksDirOnServer', AchunksDirOnServer);

                PostData.AddFile('attach', ChunksInfoPath, 'application/x-rar-compressed');
              //  PostData.AddFormField('action', 'post');



                MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/SendChunksInfo', PostData);

               if MyServerResponse<>'ok' then
               raise Exception.Create('Server Response '+MyServerResponse);


                Application.ProcessMessages;
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;



end;









{Creating dir on Server}
procedure THTTPRequests2.CreateDirOnServer(dir:string; MyServerResponse:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/CreateDirOnServer'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('DirectoryToCreate', dir);


                MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/CreateDirOnServer', PostData);

                if MyServerResponse<>'ok' then
                raise Exception.Create(MyServerResponse);

                Application.ProcessMessages;


              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;
end;

//-----------------------------------------------------------------------------------------


procedure THTTPRequests2.DeleteDirOnServer(dir:string; MyServerResponse:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/CreateDirOnServer'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('DirectoryToDelete', dir);


              //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
              //  PostData.AddFormField('action', 'post');


                 MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/DeleteDirOnServer', PostData);

                 if MyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+MyServerResponse);

                Application.ProcessMessages;



               
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;
end;




procedure THTTPRequests2.DeleteFileOnServer(AFilePath:string; AMyServerResponse:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/DeleteFileOnServer';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('Filepath', AFilePath);



                 AMyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/DeleteFileOnServer', PostData);

                 if AMyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+ AMyServerResponse);

                Application.ProcessMessages;


              finally

                if(Assigned(PostData)) then PostData.Free;

              end;



    end;


end;
end;







{Creating CurrentDayDir on Server
Example public/files/User_ID123/2016/10/28
}

procedure THTTPRequests2.CreateCurrentDayDirOnServer;

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;

begin

  DecodeDate(Now, Year, Month, Day);

  // building dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString;


  CreateDirOnServer(dir,MyServerResponse);
  if MyServerResponse<>'ok' then
  raise Exception.Create(MyServerResponse);


end;

//------------------------------------------------------------

{Creating CurrentDayDir on Server
Example public/files/User_ID123/2016/10/28
}

procedure THTTPRequests2.CreateCurrentDayDirThumbsOnServer;

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;


begin

  DecodeDate(Now, Year, Month, Day);

  // buildind dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString+'\'+
  'thumbs';

  CreateDirOnServer(dir,MyServerResponse);
  if MyServerResponse<>'ok' then
  raise Exception.Create(MyServerResponse);


end;

//---------------------------------------------------------------

{Creates Folder for File Chunks on Server}
procedure THTTPRequests2.CreateTempFolderForFileChunks(Filename:string);

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;

begin

  DecodeDate(Now, Year, Month, Day);

  // buildind dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString+'\'+
  'temp'+'\'+
  Filename
  ;


CreateDirOnServer(dir,MyServerResponse);
if MyServerResponse<>'ok' then
raise Exception.Create(MyServerResponse);

end;

//-----------------------------------------------------------------

{Deleting Folder for File Chunks on Server}
procedure THTTPRequests2.DeleteTempFolderForFileChunks(Filename:string);

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;


begin

  DecodeDate(Now, Year, Month, Day);

  // buildind dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString+'\'+
  'temp'+'\'+
  Filename
  ;

DeleteDirOnServer(dir,MyServerResponse);

end;



procedure THTTPRequests2.GatherFileFromChunks(AChunksDir, AOutPutDir, AOutPutFileName: string);
var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;
  MyServerResponse: string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/GatherFileFromChunks'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('AChunksDir', AChunksDir);
                PostData.AddFormField('AOutPutDir', AOutPutDir);
                PostData.AddFormField('AOutPutFileName', AOutPutFileName);


              //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
              //  PostData.AddFormField('action', 'post');

              MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/GatherFileFromChunks', PostData);

                if MyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+MyServerResponse);


              //  Application.ProcessMessages;
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;
end;




function StringToOleVariant(const Value: string): OleVariant;
  var Data: PByteArray;
      ss: TStringStream;
begin
  Result:=null;
  if Value='' then Exit;
  ss:=TStringStream.Create(Value);
  try
    Result := VarArrayCreate ([0, ss.Size - 1], varByte);
    Data := VarArrayLock(Result);
    try
      ss.Position := 0;
      ss.ReadBuffer(Data^, ss.Size);
    finally
      VarArrayUnlock(Result);
    end;
  finally
    ss.Free;
  end;
end;



 {Sending PostParams}
procedure THTTPRequests2.SendPostParamsForTest;

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;

  RussianWord: string;

begin



    with VisualFrame_HTTP_UnitVar do begin


    begin


      if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

        PostData := TIdMultiPartFormDataStream.Create;




                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/SomeURICommand';
                   // idHTTP.Request.ContentType := 'multipart/form-data';

                   idHTTP.Request.ContentType := 'application/x-www-form-urlencoded';





                    RussianWord:=TNetEncoding.URL.Encode('Русское слово'); // IdHTTP.URL.ParamsEncode('Русское слово');



                    PostData.AddFormField('SomePOSTParam1',RussianWord);
                    PostData.AddFormField('SomePOSTParam2','public\files\SomeUser_ID123\2016\11\2\temp\SynKernelD{F1B66A6B-91A3-4D5F-8376-FBCD425CC3CD}.log');


                   // PostData.AddFormField('SomePOSTParam1','SomePostParamValue1');
                   // PostData.AddFormField('SomePOSTParam2','SomePostParamValue2');

                  //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
                  //  PostData.AddFormField('field2', 'msg2');
                  //  PostData.AddFormField('action', 'post');

                    idHTTP.Post(HTTPServerToRequest+'/SomeURICommand', PostData);



                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;



                    //  ShowMessage('idHTTP Sent OK');

                  end;


    end;


end;
end;







end.
