Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Internet
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 08-10-2015
josepicd josepicd is offline
Miembro
 
Registrado: jun 2015
Posts: 57
Poder: 9
josepicd Va por buen camino
GetFTPFile no actualiza

Buenas de nuevo gente. a ver una pregunta.

Tengo una camara IP, que va haciendo disparos y guarda la foto como imagen.bmp.
A traves de ftp me conecto a la camara y hago un getfile de imagen.bmp para ir viendo lo que la camara va grabando.
Si hago un FTP a traves de DOS y un get todo funciona correctamente.
Si utilizo la rutina que posteo a continuacion, solo funciona la primera vez, las siguientes parece como si el ftp utilizase cache, ya que siempre me hace get de la primera imagen. Alguien ve donde estoy fallando?


Código Delphi [-]
function FtpDownloadFile(strHost, strUser, strPwd: string;
  Port: Integer; ftpDir, ftpFile, TargetFile: string; ProgressBar: TProgressBar; lbl : TLabel): Boolean;

  function FmtFileSize(Size: Integer): string;
  begin
    if Size >= $F4240 then
      Result := Format('%.2f', [Size / $F4240]) + ' Mb'
    else
    if Size < 1000 then
      Result := IntToStr(Size) + ' bytes'
    else
      Result := Format('%.2f', [Size / 1000]) + ' Kb';
  end;

const
  READ_BUFFERSIZE = 4096;  // or 256, 512, ...
var
  hNet, hFTP, hFile: HINTERNET;
  buffer: array[0..READ_BUFFERSIZE - 1] of Char;
  bufsize, dwBytesRead, fileSize: DWORD;
  sRec: TWin32FindData;
  strStatus: string;
  LocalFile: file;
  bSuccess: Boolean;
begin
  Result := False;
  DeleteFile( PChar(TargetFile));

  { Open an internet session }
  hNet := InternetOpen('Program_Name', // Agent
                        INTERNET_OPEN_TYPE_PRECONFIG, // AccessType
                        nil,  // ProxyName
                        nil, // ProxyBypass
                        0); // or INTERNET_FLAG_ASYNC / INTERNET_FLAG_OFFLINE

  {
    Agent contains the name of the application or
    entity calling the Internet functions
  }


  { See if connection handle is valid }
  if hNet = nil then
  begin
    ShowMessage('Unable to get access to WinInet.Dll');
    Exit;
  end;

  { Connect to the FTP Server }
  hFTP := InternetConnect(hNet, // Handle from InternetOpen
                          PChar(strHost), // FTP server
                          port, // (INTERNET_DEFAULT_FTP_PORT),
                          PChar(StrUser), // username
                          PChar(strPwd),  // password
                          INTERNET_SERVICE_FTP, // FTP, HTTP, or Gopher?
                          0, // flag: 0 or INTERNET_FLAG_PASSIVE
                          0);// User defined number for callback

  if hFTP = nil then
  begin
    InternetCloseHandle(hNet);
    ShowMessage(Format('Host "%s" is not available',[strHost]));
    Exit;
  end;

  { Change directory }
  if ( ftpDir = '') then bSuccess := true
                    else bSuccess := FtpSetCurrentDirectory(hFTP, PChar(ftpDir));

  if not bSuccess then
  begin
    InternetCloseHandle(hFTP);
    InternetCloseHandle(hNet);
    ShowMessage(Format('Cannot set directory to %s.',[ftpDir]));
    Exit;
  end;

  { Read size of file }
//  if FtpFindFirstFile(hFTP, PChar(ftpFile), sRec, 0, INTERNET_FLAG_RELOAD) <> nil then
  if FtpFindFirstFile(hFTP, PChar(ftpFile), sRec, 0, 0) <> nil then
  begin
    fileSize := sRec.nFileSizeLow;
    // fileLastWritetime := sRec.lastWriteTime
  end else
  begin
    InternetCloseHandle(hFTP);
    InternetCloseHandle(hNet);
    ShowMessage(Format('Cannot find file ',[ftpFile]));
    Exit;
  end;

  { Open the file }
  hFile := FtpOpenFile(hFTP, // Handle to the ftp session
                       PChar(ftpFile), // filename
                       GENERIC_READ, // dwAccess
                       FTP_TRANSFER_TYPE_BINARY, // dwFlags
                       0); // This is the context used for callbacks.

  if hFile = nil then
  begin
    InternetCloseHandle(hFTP);
    InternetCloseHandle(hNet);
    Exit;
  end;

  { Create a new local file }

  AssignFile(LocalFile, TargetFile);
  {$i-}
  Rewrite(LocalFile, 1);
  {$i+}

  if IOResult <> 0 then
  begin
    InternetCloseHandle(hFile);
    InternetCloseHandle(hFTP);
    InternetCloseHandle(hNet);
    Exit;
  end;

  dwBytesRead := 0;
  bufsize := READ_BUFFERSIZE;

  while (bufsize > 0) do
  begin
    Application.ProcessMessages;

    if not InternetReadFile(hFile,
                            @buffer, // address of a buffer that receives the data
                            READ_BUFFERSIZE, // number of bytes to read from the file
                            bufsize) then Break; // receives the actual number of bytes read

    if (bufsize > 0) and (bufsize <= READ_BUFFERSIZE) then
      BlockWrite(LocalFile, buffer, bufsize);
    dwBytesRead := dwBytesRead + bufsize;

    { Show Progress }
    if not ( ProgressBar = nil) then
      ProgressBar.Position := Round(dwBytesRead * 100 / fileSize);
    if not ( lbl = nil) then
      lbl.Caption := Format('%s of %s / %d %%',[FmtFileSize(dwBytesRead),FmtFileSize(fileSize) ,ProgressBar.Position]);
  end;

  CloseFile(LocalFile);

  InternetCloseHandle(hFile);
  InternetCloseHandle(hFTP);
  InternetCloseHandle(hNet);
  Result := True;
end;
Responder Con Cita
  #2  
Antiguo 08-10-2015
aposi aposi is offline
Miembro
 
Registrado: dic 2006
Posts: 146
Poder: 18
aposi Va por buen camino
Hola
donde utilizas la funcion GetFTPFile??
En la funcion que has pasado es solo para descargar un fichero que le pasas como parametro...
Entiendo que tienes que llamar a la funcion tantas veces como resultados obtengas de GetFTPFile
Responder Con Cita
  #3  
Antiguo 08-10-2015
aposi aposi is offline
Miembro
 
Registrado: dic 2006
Posts: 146
Poder: 18
aposi Va por buen camino
Creo que lo que necesitas es esto
http://www.clubdelphi.com/foros/showthread.php?t=35510
Responder Con Cita
  #4  
Antiguo 08-10-2015
josepicd josepicd is offline
Miembro
 
Registrado: jun 2015
Posts: 57
Poder: 9
josepicd Va por buen camino
La funcion la llamo dentro del cuerpo del programa, tengo un timer que cada 60 segundos llama a la function y carga el bmp en un picture.

Código Delphi [-]
FtpDownloadFile( '192.168.1.12", 'admin', '1234', 21, '.', 'imagen.bmp', 'd:\imagen.bmp', nil, nil);
picture.loadfromfile( 'd:\imagen.bmp');
Responder Con Cita
  #5  
Antiguo 08-10-2015
aposi aposi is offline
Miembro
 
Registrado: dic 2006
Posts: 146
Poder: 18
aposi Va por buen camino
Con tu codigo cada 60 segundos te va adescargar la imagen.bmp
si lo que quieres es descargar todas las imagenes que ha creado la camara cada 60 segundos tienes que hacer un list del ftp y descargar todas las imagenes
Responder Con Cita
  #6  
Antiguo 08-10-2015
josepicd josepicd is offline
Miembro
 
Registrado: jun 2015
Posts: 57
Poder: 9
josepicd Va por buen camino
Exacto, esa es la idea, unicamente quiero descargar "imagen.bmp", solo una imagen.

Te cuento, la camara hace una foto cuando detecta movimiento y guarda la foto hecha en un servidor interno que lleva incorporada la propia camara, le pone el nombre imagen.bmp, cuando hace otra foto machaca la antigua, por lo que en el server ftp solo hay una foto y es la ultima hecha por la camara.

Cuando yo me conecto y hago el get, obtengo la foto que tiene y la muestro por pantalla, pero la segunda vez que pido (esto me lo supongo yo) windows o quien sea detecta que la foto sobre la que quiero hacer el get tiene el mismo nombre y mismo tamaño por que lo que la que me devuelve no es la que realmente tiene el servidor ftp sino la que windows almacena en su cache.

Para asegurarme hago esto (y siempre obtengo la primera foto), si cierro y abro la aplicacion, la primera vez funciona, luego no.

Ciclo cada 60 segundos
delete d:\imagen.bmp
getfile del server ftp de la cambara hacia d:\imagen.bmp
mostrar d:\imagen.bmp
Fin ciclo
Responder Con Cita
  #7  
Antiguo 08-10-2015
Avatar de Casimiro Notevi
Casimiro Notevi Casimiro Notevi is offline
Moderador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.037
Poder: 10
Casimiro Notevi Tiene un aura espectacularCasimiro Notevi Tiene un aura espectacular
No sé si no he comprendido algo, pero me parece muy complicado.
Un copia-pega de ejemplo:

Código Delphi [-]
uses
  Windows, Messages, ......, IdFTP, IdComponent;


procedure DescargarArchivo( sArchivo: String );
var
  FTP: TIdFTP;
begin
  FTP := TIdFTP.Create( nil );
  FTP.OnWork := FTPWork;
  FTP.Username := 'usuario';
  FTP.Password := 'miclave';
  FTP.Host := 'miftp.midominio.com';

  try
    FTP.Connect;
  except
    raise Exception.Create( 'No se ha podido conectar con el servidor ' + FTP.Host );
  end;

  FTP.ChangeDir( '/misarchivos/copiaseguridad/' );

  if FileExists( sArchivo ) then
    DeleteFile( sArchivo );
    
  FTP.Get( ExtractFileName( sArchivo ), sArchivo, False, False );
    
  FTP.Disconnect;
  FTP.Free;
end;
Responder Con Cita
  #8  
Antiguo 08-10-2015
josepicd josepicd is offline
Miembro
 
Registrado: jun 2015
Posts: 57
Poder: 9
josepicd Va por buen camino
Thumbs up

Casimiro gracias por el codigo, lo probare a ver que tal funciona.

El que he puesto yo hace uso de la libreria wininet.dll y no hace servir componentes, el problema es que no entiendo porque falla. Pero bueno, no le dare mas vueltas y a producir!!!

Gracias de nuevo, ya os informo si usando TIdFTP me funciona. Aposi, gracias a ti tambien.
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

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
Procedimiento no actualiza Rockin Firebird e Interbase 5 25-10-2011 10:32:50
no se actualiza armando Firebird e Interbase 2 04-12-2009 01:22:30
No actualiza IBQ trex2000 Conexión con bases de datos 2 19-01-2007 20:52:20
No actualiza trex2000 Firebird e Interbase 2 28-01-2005 23:43:20
No actualiza . . . Agar23 Conexión con bases de datos 12 25-05-2004 09:27:52


La franja horaria es GMT +2. Ahora son las 08:45:49.


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