В прошлом посте про мультипоточную загрузку я столкнулся с некорректной индикацией процесса загрузки на сервер. Сама загрузка работала для нескольких файлов. А вот визуализация только для 1 файла. Поэтому, приходилось выкручиваться с таймерами. И я бы оставил этот вопрос, если бы не наткнулся на вот это обсуждение на stackoverflow, в котором указывалась ссылка на интересный ресурс про активный и пассивный режимы FTP протокола.
Я немного переделал код, и у меня получилась следующая картина
Весь секрет был в одной строчке…
1 |
fidFTP.Passive:=true; // <<Секрет успешной мультизагрузки... |
После этого данные стали поступать в процедурах Work и WorkBegin.
Код потока передачи данных стал следующим
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
unit uPSFTPUploadThread; interface uses uPSMultiUploadForm,ShellApi, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,syncobjs,uVisualFrame_PSFTPClient, //idFTP IdBaseComponent, IdComponent,IdException, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, Vcl.StdCtrls,uPSFTPUploadFrame,IdFTPCommon; type TFTPUploadThread = class(TThread) private { Private declarations } fidFTP:TIdFTP; FSourceFileName:string; FFileSize:Int64; FFileSizeString: string; FIndexInUploadProgressList:integer; FFTPClient:TVisualFrame; FDestFileName:string; FCriticalSection:TCriticalSection; procedure IdFTPAfterPut(Sender: TObject); procedure IdFTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure IdFTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure IdFTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); procedure IdFTPWorkEnd(ASender: TObject; AWorkMode: TWorkMode); function FindIndex: integer; public property FTPClient:TVisualFrame read FFTPClient write FFTPClient; property idFTP:TIdFTP read fidFTP write fidFTP; property FileSize:Int64 read FFileSize write FFileSize; property FileSizeString: string read FFileSizeString write FFileSizeString; property IndexInUploadProgressList:Integer read FIndexInUploadProgressList write FIndexInUploadProgressList; property CriticalSection:TCriticalSection read FCriticalSection write FCriticalSection; property SourceFileName:string read FSourceFileName write FSourceFileName; property DestFileName:string read FDestFileName write FDestFileName; protected procedure Execute; override; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TFTPUploadThread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { TFTPUploadThread } procedure TFTPUploadThread.Execute; var i: integer; begin fidFTP:=TIdFTP.Create(nil); //Присваиваем события компоненту fidFTP fidFTP.OnAfterPut:=IdFTPAfterPut; fidFTP.OnWorkBegin:=IdFTPWorkBegin; fidFTP.OnWork:=IdFTPWork; fidFTP.OnStatus:=IdFTPStatus; fidFTP.OnWorkEnd:=IdFTPWorkEnd; fidFTP.Host:=FTPClient.FTPParams.Host;// 'localhost'; fidFTP.Port:=FTPClient.FTPParams.Port;// 22; fidFTP.Username:=FTPClient.FTPParams.Username; //'Login'; fidFTP.Password:=FTPClient.FTPParams.Password; //'Password'; fidFTP.Passive:=true; // <<Секрет успешной мультизагрузки... if not fidFTP.Connected then fidFTP.Connect; if not fidFTP.Connected then Exit; CriticalSection:=TCriticalSection.Create; CriticalSection.Enter; if FTPClient=nil then Exit; if SourceFileName='' then exit; try with FTPClient do begin //Enabled:=false; // <<<Блокировка формы PutThreadsInProcess:=PutThreadsInProcess+1; begin fidFTP.MakeDir(FTPClient.FTPParams.UploadDir); fidFTP.ChangeDir(FTPClient.FTPParams.UploadDir); //fidFTP.TransferType := ftBinary; fidFTP.Put(SourceFileName,DestFileName); end; PutThreadsInProcess:=PutThreadsInProcess-1; //Enabled:=true; // Разблокировка формы //if PutThreadsInProcess=0 then MultiUploadForm.Hide; // << Закроет окно по завершении end; finally //fidFTP.Disconnect; // Не включать... FreeAndNil(fidFTP); CriticalSection.Leave; FreeAndNil(FCriticalSection); end; { Place thread code here } end; function TFTPUploadThread.FindIndex:integer; var i: Integer; begin for i := 0 to FTPClient.UploadProgressList.Count-1 do begin if TfUploadProgress(FTPClient.UploadProgressList.Items[i]). lUploadFileName.Caption=ExtractFileName(SourceFileName) then Result:=i; end; end; procedure TFTPUploadThread.IdFTPAfterPut(Sender: TObject); begin //ShowMessage('File Successfully Uploaded'); end; procedure TFTPUploadThread.IdFTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin // FTPClientForm.MultiUploadForm.Caption:=IndexInUploadProgressList.ToString; FileSize:=AWorkCountMax; //Getting FileSizeString if AWorkCountMax<1024 then FileSizeString:=AWorkCountMax.ToString()+' Bytes'; if (AWorkCountMax>1024) and (AWorkCountMax<(1024*1024)) then FileSizeString:=(Trunc(AWorkCountMax/1024)).ToString()+' KB'; if (AWorkCountMax>(1024*1024)) {and (FileSize<(1024*1024*1024))} then FileSizeString:=(Trunc(AWorkCountMax/(1024*1024))).ToString()+' MB'; with TfUploadProgress(FTPClient.UploadProgressList. Items[FindIndex]) do ProgressBar.Max:=100; end; procedure TFTPUploadThread.IdFTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); var CurrentBytesString:string; begin //Getting CurrentBytes if AWorkCount<1024 then CurrentBytesString:=AWorkCount.ToString()+' Bytes'; if (AWorkCount>1024) and (AWorkCount<(1024*1024)) then CurrentBytesString:=(Trunc(AWorkCount/1024)).ToString()+' KB'; if (AWorkCount>(1024*1024)) {and (FileSize<(1024*1024*1024))} then CurrentBytesString:=(Trunc(AWorkCount/(1024*1024))).ToString()+' MB'; with TfUploadProgress(FTPClient.UploadProgressList. Items[FindIndex]) do begin ProgressBar.Position:=Trunc((AWorkCount/Filesize)*100); lFileSize.Caption:=CurrentBytesString+' / '+FileSizeString; end; end; procedure TFTPUploadThread.IdFTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin with TfUploadProgress(FTPClient.UploadProgressList. Items[FindIndex]) do begin lUploadStatus.Caption:=AStatusText; //if AStatusText='Transfer Complete' then ProgressBar.Position:=100; end; end; procedure TFTPUploadThread.IdFTPWorkEnd(ASender: TObject; AWorkMode: TWorkMode); begin with TfUploadProgress(FTPClient.UploadProgressList. Items[FindIndex]) do ProgressBar.position:=ProgressBar.Max; end; end. |
В главном же модуле тоже произошли кое какие изменения
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 |
unit uVisualFrame_PSFTPClient; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP,IdException,Contnrs,uPSFTPUploadFrame,uPSMultiUploadForm,System.IOUtils; type TFTPParams=record Host:string; Port:integer; Username:string; Password:string; UploadDir:string; UploadDirTemp:string; end; type TVisualFrame = class(TFrame) PageControl: TPageControl; tsInsertFromWeb: TTabSheet; bInsertLinkToPage: TBitBtn; OpenDialog: TOpenDialog; pLinks: TPanel; leLink: TLabeledEdit; leLinkName: TLabeledEdit; ScrollBox1: TScrollBox; IdFTP: TIdFTP; tsMediaLibrary: TTabSheet; pControlsPanel: TPanel; cbFileTypes: TComboBox; eSearch: TEdit; bSearch: TBitBtn; bTest: TButton; tsUploadToServer: TTabSheet; bChooseFiles: TBitBtn; tsUploads: TTabSheet; ScrollBoxUploads: TScrollBox; procedure FrameResize(Sender: TObject); procedure eSearchClick(Sender: TObject); procedure bTestClick(Sender: TObject); procedure bChooseFilesClick(Sender: TObject); private // Мультиаплоад форма и параметры FMultiUploadForm:TfMultiUpload; FFTPParams:TFTPParams; //Визуализация многопоточной загруки FLastUploadProgress:integer; FUploadProgressList:TObjectList; //Лист потоков загрузки на FTP сервер FPutThreadsList:TObjectList; FLastPutThreadNumber:integer; // Списки файлов на клиенте и на сервере FFilesOnClient:TStringList; // Список файлов к загрузке FFilesOnServer:TStringList; // Список файлов и папок... //Число потоков FPutThreadsInProcess:integer; procedure CenterElements; procedure FillFilesOnServer; procedure PutFileOnServer(FileName: string); procedure Test; public constructor Create(AOwner:TComponent); override; destructor Destroy; // Мультиаплоад форма и параметры property MultiUploadForm:TfMultiUpload read FMultiUploadForm write FMultiUploadForm; property FTPParams:TFTPParams read FFTPParams write FFTPParams; //Файлы на сервере и на клиенте property FilesOnClient:TStringList read FFilesOnClient write FFilesOnClient; property FilesOnServer:TStringList read FFilesOnServer write FFilesOnServer; //___ property UploadProgressList:TObjectList read FUploadProgressList write FUploadProgressList; property PutThreadsList:TObjectList read FPutThreadsList write FPutThreadsList; property LastPutThreadNumber:integer read FLastPutThreadNumber write FLastPutThreadNumber; //Число текущих потоков property PutThreadsInProcess:integer read FPutThreadsInProcess write FPutThreadsInProcess; //Публичные функции и процедуры function IsFTPServerConnectionOk:Boolean; function Translit(s: string): string; function GetFileSize(FileName: String; var FileSize: Int64): string; end; implementation uses uPSFTPUploadThread; {$R *.dfm} { TVisualFrame } function TVisualFrame.GetFileSize(FileName: String; var FileSize:Int64): string; var FS: TFileStream; SizeInBytes:Int64; begin try FS := TFileStream.Create(Filename, fmOpenRead); try FileSize:=FS.Size; if FileSize<1024 then Result:=FileSize.ToString()+' Bytes'; if (FileSize>1024) and (FileSize<(1024*1024)) then Result:=(Trunc(FileSize/1024)).ToString()+' KB'; if (FileSize>(1024*1024)) {and (FileSize<(1024*1024*1024))} then Result:=(Trunc(FileSize/(1024*1024))).ToString()+' MB'; finally FS.Free; end; except on E:Exception do begin FileSize := -1; Result:='-1'; raise Exception.Create(E.ClassName+' Exception Raised : ' +#13#10+#13#10+E.Message); end; end; end; procedure TVisualFrame.bChooseFilesClick(Sender: TObject); var i: Integer; DestName:string; JoinedString: string; begin if not IsFTPServerConnectionOk then exit; FilesOnClient.Clear; FillFilesOnServer; if OpenDialog.Execute then // Отправляем на сервер for i := 0 to OpenDialog.Files.Count-1 do PutFileOnServer(OpenDialog.Files[i]); // if not MultiUploadForm.Visible then MultiUploadForm.ShowModal; end; procedure TVisualFrame.bTestClick(Sender: TObject); begin Test; { ShowMessage( ExtractFileDir(Application.ExeName)+'\temp' ); } //if IsFTPServerConnectionOk then ShowMessage('FTPConnectionOk'); end; procedure TVisualFrame.CenterElements; begin leLink.Width:=20; leLink.Width:=Self.Width-2*leLink.Left; //Self.Width-leLink.Left-leLink.Width=leLink.Left; leLinkName.Width:=20; leLinkName.Width:=Self.Width-2*leLinkName.Left; //Центрируем кнопку выбора файлов по горизонтали и вертикали bChooseFiles.Left:=Trunc((Self.Width/2)-(bChooseFiles.Width/2)); bChooseFiles.Top:=Trunc((Self.Height/2)-(bChooseFiles.Height/2)); //Центрируем кнопку вставки ссылки //bInsertLinkToPage.Left:=Trunc((Self.Width/2)-(bInsertLinkToPage.Width/2)); //bChooseFiles.Top:=Self.Height-bChooseFiles.Height-20; end; constructor TVisualFrame.Create(AOwner: TComponent); begin inherited; MultiUploadForm:=TfMultiUpload.Create(Self); with FFTPParams do begin Host:='localhost'; Port:=22; Username:='Login'; Password:='Password'; UploadDir:='/files'; UploadDirTemp:='/files/temp'; end; CenterElements; FFilesOnClient:=TStringList.Create; // Список файлов к загрузке FFilesOnServer:=TStringList.Create; // Список файлов и папок... //Листы объектов FPutThreadsList:=TObjectList.Create; FPutThreadsList.OwnsObjects:=false; // << Потоки сами самоудаляются FUploadProgressList:=TObjectList.Create; end; destructor TVisualFrame.Destroy; begin ReportMemoryLeaksOnShutdown:=true; FreeAndNil(FPutThreadsList); FreeAndNil(FUploadProgressList); FreeAndNil(FFilesOnClient); FreeAndNil(FFilesOnServer); end; procedure TVisualFrame.eSearchClick(Sender: TObject); begin if eSearch.Text='Поиск...' then eSearch.Text:=''; end; procedure TVisualFrame.FrameResize(Sender: TObject); begin CenterElements; end; function TVisualFrame.IsFTPServerConnectionOk: Boolean; begin Result:=false; with idFTP do begin Host:=FTPParams.Host;// 'localhost'; //FTP-сервер Port:=FTPParams.Port;// 22; //порт ФТП сервера Username:=FTPParams.Username;// 'Логин'; Password:=FTPParams.Password;// 'Пароль'; end; try idFTP.Connect; try try if IdFTP.Connected then Result:=true; finally idFTP.Disconnect; end; except //Other exceptions on E: EIdException do begin raise Exception.Create(E.ClassName+' An network error occurred during communication: ' +#13#10+#13#10+E.Message); end; on E: Exception do begin raise Exception.Create(E.ClassName+' An unknown error occurred during communication: ' +#13#10+#13#10+E.Message); end; end; except // Catching Connection Exceptions on E: EIdException do begin raise Exception.Create(E.ClassName+' An network error occurred while trying to connect: ' +#13#10+#13#10+E.Message); end; on E: Exception do begin raise Exception.Create(E.ClassName+'An unknown error occurred while trying to connect: ' +#13#10+#13#10+E.Message); end; end; end; procedure TVisualFrame.Test; var SourceFileName: string; DestFileName: string; SourceFileNameServer: string; DestFileNameServer: string; s: string; SplittedString: TArray<String>; NewNameOnServer: string; begin with idFTP do begin Host:=FTPParams.Host;// 'localhost'; //FTP-сервер Port:=FTPParams.Port;// 22; //порт ФТП сервера Username:=FTPParams.Username;// 'Логин'; Password:=FTPParams.Password;// 'Пароль'; Connect; end; if OpenDialog.Execute then begin SourceFileName:=OpenDialog.FileName; DestFileName:=Translit(ExtractFileName(OpenDialog.FileName)); //Создаем и меняем поддиректорию idFTP.MakeDir(FTPParams.UploadDirTemp); // /files/temp idFTP.ChangeDir(FTPParams.UploadDirTemp); //Переносим туда файл // idFTP.TransferType := ftBinary; // idFTP.Put(SourceFileName,DestFileName,false); //Переименовываем его в поддиректории // SourceFileNameServer:=FTPParams.UploadDirTemp+'/'+DestFileName; SplittedString:=DestFileName.Split(['.']); SplittedString[0]:=SplittedString[0]+Random(10000).ToString; NewNameOnServer:=FTPParams.UploadDirTemp+'/'+SplittedString[0]+'.'+SplittedString[1]; idFTP.Rename(SourceFileNameServer,NewNameOnServer); idFTP.Put(SourceFileName,SplittedString[0]+'.'+SplittedString[1],false); { // И ещё раз... SourceFileNameServer:=NewNameOnServer; DestFileNameServer:=FTPParams.UploadDir+'/'+DestFileName; ShowMessage(SourceFileNameServer); ShowMessage(DestFileNameServer); // idFTP.Rename(SourceFileNameServer,DestFileNameServer); } //IdFTP.Put(SourceFileNameServer,DestFileNameServer); // ShowMessage(idFTP.RetrieveCurrentDir); // ShowMessage(SourceFileNameServer); // ShowMessage(DestFileNameServer); // idFTP.Rename(); //Переносим в основную директорию /files //Удаляем из поддиректории /files/temp end; IdFTP.Disconnect; end; function TVisualFrame.Translit(s: string): string; const rus: string = 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя'; lat: array[1..33] of string = ('a', 'b', 'v', 'g', 'd', 'e', 'yo', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'ts', 'ch', 'sh', 'shch', '''', 'y', '''', 'e', 'yu', 'ya'); var p, i, l: integer; begin s:=widelowercase(s); Result := ''; l := Length(s); for i := 1 to l do begin p := Pos(s[i], rus); if p<1 then Result := Result + s[i] else Result := Result + lat[p]; end; end; procedure TVisualFrame.PutFileOnServer(FileName: string); var s: string; SplittedString: TArray<String>; NewNameOnServer: string; FileSize: Int64; begin { FilesOnClient.Add(ExtractFileName(OpenDialog.Files[i])); // Проверяем, есть ли такой файл на сервере - придумываем ему новое имя if FilesOnServer.IndexOf(ExtractFileName(OpenDialog.Files[i])) <> -1 then begin // Придумываем новое имя, если файл с таким именем уже есть на сервере s := ExtractFileName(OpenDialog.Files[i]); SplittedString := s.Split(['.']); SplittedString[0] := SplittedString[0] + Random(10000).ToString; //s:=SplittedString[0]+'.'+SplittedString[1]; //NewNameOnServer:=SplittedString[0]+'.'+SplittedString[1]; NewNameOnServer := NewNameOnServer.Join('.', [SplittedString[0], SplittedString[1]]); showmessage(s); end; } //Визуализация загрузки FLastUploadProgress := UploadProgressList.Add(TfUploadProgress.Create(Self)); with TfUploadProgress(UploadProgressList.Items[FLastUploadProgress]) do begin Name := 'fUploadProgress' + FLastUploadProgress.ToString; // Parent := MultiUploadForm.ScrollBox; Parent:=ScrollBoxUploads; PageControl.TabIndex:=3; Align := alTop; //Имя файла lUploadFileName.Caption := ExtractFileName(FileName); //Указываем размер lFileSize.Caption := GetFileSize(FileName, FileSize); //Настраиваем ProgressBar ProgressBar.Max := FileSize; ProgressBar.Step := Trunc(FileSize / 100); end; // Непосредственно отправка на сервер - в потоке... begin //Собственно загрузка ВАРИАНТ2 - Создание потока через ObjectList LastPutThreadNumber := PutThreadsList.Add(TFTPUploadThread.Create(true)); with TFTPUploadThread(PutThreadsList.Items[LastPutThreadNumber]) do begin FTPClient := Self; FreeOnTerminate := True; IndexInUploadProgressList := FLastUploadProgress; SourceFileName := FileName; if FilesOnServer.IndexOf( ExtractFileName(FileName) )<>-1 then begin DestFileName := Translit(ExtractFileName(SourceFileName)); SplittedString:=DestFileName.Split(['.']); SplittedString[0]:=SplittedString[0]+Random(10000000).ToString; NewNameOnServer:=FTPParams.UploadDir+'/'+SplittedString[0]+'.'+SplittedString[1]; DestFileName:=NewNameOnServer; end else DestFileName:=ExtractFileName(SourceFileName); // ShowMessage(DestFileName); Start; end; end; end; //-----Список файлов с сервера procedure TVisualFrame.FillFilesOnServer; var I: integer; begin with idFTP do begin Host:=FTPParams.Host;// 'localhost'; //FTP-сервер Port:=FTPParams.Port;// 22; //порт ФТП сервера Username:=FTPParams.Username;// 'Логин'; Password:=FTPParams.Password;// 'Пароль'; end; try idFTP.Connect; try try if IdFTP.Connected then begin //ОСНОВНАЯ РАБОТА ЗДЕСЬ with idFTP do begin // Создаем директорию и меняем её MakeDir(FTPParams.UploadDir); ChangeDir(FTPParams.UploadDir); List; // <<Собираем список папок и файлов FilesOnServer.Clear; for i := 0 to IdFTP.DirectoryListing.Count-1 do begin FilesOnServer.Add(IdFTP.DirectoryListing[i].FileName); end; end; end; finally idFTP.Disconnect; end; except //Other exceptions on E: EIdException do begin raise Exception.Create(E.ClassName+' An network error occurred during communication: ' +#13#10+#13#10+E.Message); end; on E: Exception do begin raise Exception.Create(E.ClassName+' An unknown error occurred during communication: ' +#13#10+#13#10+E.Message); end; end; except // Catching Connection Exceptions on E: EIdException do begin raise Exception.Create(E.ClassName+' An network error occurred while trying to connect: ' +#13#10+#13#10+E.Message); end; on E: Exception do begin raise Exception.Create(E.ClassName+'An unknown error occurred while trying to connect: ' +#13#10+#13#10+E.Message); end; end; end; end. |