Club Delphi  
    Paypal   FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Internet
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Colaboración Paypal con ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 19-06-2025
pruz pruz is offline
Miembro
 
Registrado: sep 2003
Posts: 225
Poder: 23
pruz Va por buen camino
Red face ERROR al compara archivos FTP

Buenas amigos.
Estoy haciendo una aplicacion FTP, para subir archivos a un servidor

Necesito compara o saber si ya el archivo existe en el servidor donde voy a subirlo.

Pero me da el siguiente error "connection closed gracefully". Estoy usando Indy y el comando List. y delphi 7.
Ya verifique que la coneccion esta abierta, ya verifique el directorio donde esta la informacion.
he qui el codigo

Código Delphi [-]
   if ftp.Connected then begin
      ya_existe := False;
      FileList := TStringList.Create;

      FTP.ChangeDir(sruta);

      FTP.List(FileList, '*.pdf',True); ///aqui me da el error

      for I := 0 to FileList.Count - 1 do  begin
        if SameText(FileList.Strings[i], sArchivo) then    begin
          ya_existe := True;
          Break; // Encontramos el archivo, salimos del bucle
        end;
      end;
   end;


Gracias.
Responder Con Cita
  #2  
Antiguo 19-06-2025
navbuoy navbuoy is offline
Miembro
 
Registrado: mar 2024
Posts: 360
Poder: 3
navbuoy Va por buen camino
deberias primero hacer un List() normal para luego comprobar la estructura de listing de archivos

te paso un codigo a ver si sacas algo en claro, (RUTA_HOSTING es una cadena mia propia donde pongo el directorio, ajustalo como tu veas)

Código:
AnsiString RUTA_HOSTING = "RECROAK_GAME";
Código Delphi [-]
uses
  IdFTP, IdFTPList, IdComponent, SysUtils;

procedure VerificarArchivoFTP(IdFTP1: TIdFTP; const ArchivoABuscar: string);
var
  i: Integer;
  ExisteEnServidor: Boolean;
begin
  ExisteEnServidor := False;

  try
    IdFTP1.Connect;
    IdFTP1.ChangeDir('/'); //Se situa en el Raiz del hosting
    IdFTP1.ChangeDir('RUTA_HOSTING'); // Reemplazá por tu ruta
    IdFTP1.List;

    for i := 0 to IdFTP1.DirectoryListing.Count - 1 do
    begin
      if IdFTP1.DirectoryListing.Items[i].ItemType = ditFile then
      begin
        if AnsiCompareText(IdFTP1.DirectoryListing.Items[i].FileName, ArchivoABuscar) = 0 then
        begin
          ExisteEnServidor := True;
          Break;
        end;
      end;
    end;

    if ExisteEnServidor then
      ShowMessage('El archivo ya existe en el servidor.')
    else
      ShowMessage('El archivo no existe. Se puede subir.');
  // Aquí hacés el Put
  // IdFTP1->Put(".\\data\\Game_Design_Document.pdf");

  finally
    IdFTP1.Disconnect;
  end;
end;

�� Cómo usarlo:
Llamalo así desde un botón, por ejemplo:

Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
begin
  VerificarArchivoFTP(IdFTP1, 'miarchivo.pdf');
end;

Última edición por navbuoy fecha: 19-06-2025 a las 18:38:24.
Responder Con Cita
  #3  
Antiguo 19-06-2025
navbuoy navbuoy is offline
Miembro
 
Registrado: mar 2024
Posts: 360
Poder: 3
navbuoy Va por buen camino
perdona si algunas cosas siguen la convencion de C++ Builder, es que he tenido que convertirlo, yo programo en C++ Builder
Responder Con Cita
  #4  
Antiguo 19-06-2025
pruz pruz is offline
Miembro
 
Registrado: sep 2003
Posts: 225
Poder: 23
pruz Va por buen camino
navbuoy,
gracias por responder, pero me sigue dando el mismo error

Código Delphi [-]
if ftp.Connected then begin
      
      ExisteEnServidor := False;

      FTP.ChangeDir('/');
      FTP.ChangeDir(sruta);
      FTP.List;          ///aqui me da el mismo error

     for i := 0 to FTP.DirectoryListing.Count - 1 do begin
        if FTP.DirectoryListing.Items[i].ItemType = ditFile then begin  //supongo que el ditFile es type de archivo
        if AnsiCompareText(FTP.DirectoryListing.Items[i].FileName, sArchivo) = 0 then
        begin
          ExisteEnServidor := True;
          Break;
        end;
     // end;
    end;

    if ExisteEnServidor then
      ShowMessage('El archivo ya existe en el servidor.')
    else
      ShowMessage('El archivo no existe. Se puede subir.');

gracias
Responder Con Cita
  #5  
Antiguo 19-06-2025
navbuoy navbuoy is offline
Miembro
 
Registrado: mar 2024
Posts: 360
Poder: 3
navbuoy Va por buen camino
prueba a configurar estas propiedades del componente IdFTP

tambien podria ser que Firewall o antivirus bloquea puertos pasivos
A veces parece que conecta pero al hacer List cierra la sesión.

Código:
FTP.Passive := True;
FTP.TransferType := ftBinary;
FTP.ListFormat := flUnix;
si, ditFile indica que es un archivo y no un directorio

Última edición por navbuoy fecha: 19-06-2025 a las 21:21:52.
Responder Con Cita
  #6  
Antiguo 20-06-2025
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 19.435
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Yo lo tengo configurado de esta forma:

Código Delphi [-]
  IdFTP.Passive := True;
  IdFTP.TransferType := TIdFTPTransferType.ftBinary;
Y con el código que ves más abajo (muy similar al tuyo) me funciona perfectamente.

Código Delphi [-]
var
  items:TIdFTPListItems;
...
begin
...
  try
    // Cargar contenido
    IdFTP.List;
    items := IdFTP.DirectoryListing;
    for i := 0 to (items.Count - 1) do begin
      item := idftp.directorylisting.Items[i];
      if (item.ItemType = ditFile) and AnsiContainsText(AnsiString(Item.FileName), AnsiString(MiFichero)) then begin
        ...
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #7  
Antiguo 24-06-2025
pruz pruz is offline
Miembro
 
Registrado: sep 2003
Posts: 225
Poder: 23
pruz Va por buen camino
Talking

Amigos,

les cuento traspase todo el codigo a Delphi Tokio y me da los mismos errores le envio el codigo correcto para que lo revisen,
a veces nos nublamos tanto; que pueda que sea un error tonto.

Código Delphi [-]
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdFTP, IdComponent, IdBaseComponent, IdUDPBase,
  IdUDPClient, IdSysLog, ComCtrls, IdEchoUDP;


begin


     FTP := TIdFTP.Create( nil );
     FTP.Username := 'xxxxxx';
     FTP.Password := 'xxxxx';
     FTP.Host := 'xxx.xxx.xxx.xx';
     FTp.Port := xx;
     FTP.Passive := True;
     FTP.TransferType := TIdFTPTransferType.ftBinary;  // Undeclared identifier: 'TIdFTPTransferType'


     sArchivo := 'esteArchivo.pdf' //nombre del archivo
     sOrigen  := OpenDialog1.FileName;  //ruta del origen del archivo

     sruta := '\copiar\aqui\' + sArchivo; //ruta destino

     FTP.Connect;

     try
        if ftp.Connected then begin
           ok := False;
           FTP.List(FileList, '*.pdf',True);   //aqui da el error descrito anteriormente (error "connection closed gracefully")

           for I := 0 to FileList.Count - 1 do  begin
              if SameText(FileList.Strings[i], sArchivo) then // Usa SameText para ignorar mayúsculas/minúsculas
               // if FileList.Items[i] = AFileName then // Usa esto para una comparación sensible a mayúsculas/minúsculas
              begin
               ok := True;
               Break; // Encontramos el archivo, salimos del bucle
             end;
          end;
       end;
     finally
        FileList.Free;
     end;


     if ok then begin
          ShowMessage('Archivo ya existe.');

     end else begin
          FTP.Put(  sOrigen, sRuta, false );  //subir archivo sino existe
     end;

     FTP.Disconnect;

las probe en delphi 6 y delphi tokio


Saludos,
Responder Con Cita
  #8  
Antiguo 25-06-2025
Avatar de Casimiro Noteví
Casimiro Noteví Casimiro Noteví is offline
Merodeador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.669
Poder: 10
Casimiro Noteví Tiene un aura espectacularCasimiro Noteví Tiene un aura espectacular
Está mal esa línea que muestra el error:
Código Delphi [-]
FTP.List(FileList, '*.pdf',True);
Ahí no puedes indicar que quieres listar los pdf, ahí va el directorio.


Código Delphi [-]
uses
  IdFTP, IdComponent, IdGlobal, SysUtils, Classes;

function ExistePDFEnFTP(Host, Usuario, Clave, Directorio, NombrePDF: string): Boolean;
var
  FTP: TIdFTP;
  ListaArchivos: TStringList;
  i: Integer;
begin
  Result := False;
  FTP := TIdFTP.Create(nil);
  ListaArchivos := TStringList.Create;
  try
    FTP.Host := Host;
    FTP.Username := Usuario;
    FTP.Password := Clave;
    FTP.Connect;

    if Directorio <> '' then
      FTP.ChangeDir(Directorio);

    // Obtener listado de archivos
    FTP.List(ListaArchivos, '', False);

    for i := 0 to ListaArchivos.Count - 1 do
    begin
      // Normaliza el nombre a minúsculas para evitar problemas con mayúsculas
      if SameText(ExtractFileExt(ListaArchivos[i]), '.pdf') then
      begin
        if (NombrePDF = '') or SameText(ListaArchivos[i], NombrePDF) then
        begin
          Result := True;
          Break;
        end;
      end;
    end;

    FTP.Disconnect;
  finally
    ListaArchivos.Free;
    FTP.Free;
  end;
end;
Responder Con Cita
  #9  
Antiguo 25-06-2025
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 19.435
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Para ir descartando cosas.
En el código, al menos en ese trozo, no veo la creación de FileList (imagino que está en otro sitio).

En cuanto al TransferType, prueba a añadir la unit: idFTPCommon

Por ejemplo, este código funciona (al menos no falla en el punto que tú comentas):

Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
  FTP:TIdFTP;
  ok:boolean;
  FileList:TStrings;
  i:integer;
  sArchivo:string;
begin
     FTP := TIdFTP.Create( nil );
     FTP.Username := 'demo';
     FTP.Password := 'password';
     FTP.Host := 'test.rebex.net';
     FTp.Port := 21;
     FTP.Passive := True;
     FTP.TransferType := ftBinary; 

     sArchivo := 'esteArchivo.pdf'; //nombre del archivo
{    sOrigen  := OpenDialog1.FileName;  //ruta del origen del archivo
     sruta := '\copiar\aqui\' + sArchivo; //ruta destino
}
     FileList := TStringList.Create;
     FTP.Connect;

     try
        if ftp.Connected then begin
           ok := False;
           FTP.ChangeDir('pub');
           FTP.ChangeDir('example');
           FTP.List(FileList, edtExtension.Text,True);  

           ShowMessage(Format('He encontrado <%d> ficheros', [FileList.Count]));           
           for I := 0 to FileList.Count - 1 do  begin
              if SameText(FileList.Strings[i], sArchivo) then // Usa SameText para ignorar mayúsculas/minúsculas
               // if FileList.Items[i] = AFileName then // Usa esto para una comparación sensible a mayúsculas/minúsculas
              begin
               ok := True;
               Break; // Encontramos el archivo, salimos del bucle
             end;
          end;
       end;
     finally
        FileList.Free;
     end;

     if ok then begin
       ShowMessage('Archivo ya existe.');
     end else begin
//          FTP.Put( sOrigen, sRuta, false );  //subir archivo sino existe
     end;

     FTP.Disconnect;
end;

Está compilado en Delphi7 y contra un servidor de prueba de los muchos que hay.
He comentado algunas líneas para la prueba y porque el servidor al ser de pruebas tiene restricciones (como la de no poder subir ficheros), pero para la prueba es suficiente.

Si lo ejecutas te debería dar algún resultado.
Si pruebas con extension "*.*" verás que es capaz de encontrar 16 ficheros, mientras que si pruebas con "*.pdf" obtendrás 0. Pero en ningún caso falla.
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #10  
Antiguo 25-06-2025
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 19.435
Poder: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Si este mismo código que funciona en el de pruebas, falla contra tu servidor, ya sabemos que es una configuración diferente (no es del código).

Aquí tienes una lista de servidores de pruebas, aunque si buscas encontrarás más.
https://www.smartftp.com/es-es/support/kb/2779

Según el servidor puedes probar FTP/SFTP, subidas y bajadas,...
__________________
Germán Estévez => Web/Blog
Guía de estilo, Guía alternativa
Utiliza TAG's en tus mensajes.
Contactar con el Clubdelphi

P.D: Más tiempo dedicado a la pregunta=Mejores respuestas.
Responder Con Cita
  #11  
Antiguo 25-06-2025
Avatar de Casimiro Noteví
Casimiro Noteví Casimiro Noteví is offline
Merodeador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.669
Poder: 10
Casimiro Noteví Tiene un aura espectacularCasimiro Noteví Tiene un aura espectacular
¿En qué versión puedes indicar la máscara de lo que va a listar?
FTP.List(FileList, edtExtension.Text,True);
En la versión que tengo yo, de la indy 10, ahí no va eso.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Algoritmo que compara cadenas de texto Faust Varios 2 11-06-2010 16:42:32
Compara Valores de Objetos de la misma clase Carmelo Cash OOP 14 07-04-2009 23:47:57
Error en actualizacion de archivos lgarcia Varios 2 08-06-2007 19:21:57
ayudenme compara reportbuilder?? gatoar77 Impresión 1 21-12-2005 09:10:08
Ayuda para compara datos miguel_fr Varios 1 24-06-2004 06:12:43


La franja horaria es GMT +2. Ahora son las 03:08:16.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi