Ir para conteúdo
Fórum Script Brasil
  • 0

Criar uma exceção ao chamar UrlDownloadToFile


paulobergo

Pergunta

Oi pessoal...

Antes de Mais Nada, desejo um feliz Natal e um Maravilhoso 2009 com muita saúde, saúde e saúde!

Para conseguir contornar uma dificuldade em gravar o conteúdo de algumas câmeras, precisei usar a função UrlDownloadToFile (Unit UrlMon) e o resultado foi bastante satisfatório.

Porém, hoje pela manhã, um problema na Internet provocou uma falha na captura da imagem liberada a cada segundo pela câmera e um dos programas mostrou uma mensagem de erro, indicando que o arquivo não pôde ser baixado...

O código que contém a função é este:

Function DownloadFile1(sSource1, sDest1: String): Boolean;
Begin
  Try
    Result := UrlDownloadToFile(nil, PChar(sSource1), PChar(sDest1), 0, nil) = 0;
  Except
    Result := False;
  End;

Apesar disso, o programa parou na caixa de alerta... interrompendo a gravação da câmera... o desejado é que ele continuasse tentando fazer o download da imagem....

Há alguma forma de "dizer" à "UrlDownloadToFile" para não exibir mensagem alguma em caso de falha?

Gratos! Abraços!

Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

  • 0

Apesar disso, o programa parou na caixa de alerta... interrompendo a gravação da câmera... o desejado é que ele continuasse tentando fazer o download da imagem....

Há alguma forma de "dizer" à "UrlDownloadToFile" para não exibir mensagem alguma em caso de falha?

Function DownloadFile1(sSource1, sDest1: String): Boolean;
Begin
  Try
    Result := UrlDownloadToFile(nil, PChar(sSource1), PChar(sDest1), 0, nil) = 0;
  Except
    Result := False;
  End;
Veja a sintaxe da função no help.
URLDownloadToFile Function Downloads bits from the Internet and saves them to a file. Syntax HRESULT URLDownloadToFile( LPUNKNOWN pCaller, LPCTSTR szURL, LPCTSTR szFileName, DWORD dwReserved, LPBINDSTATUSCALLBACK lpfnCB );Parameters pCaller A pointer to the controlling IUnknown interface of the calling Microsoft ActiveX component, if the caller is an ActiveX component. If the calling application is not an ActiveX component, this value can be set to NULL. Otherwise, the caller is a Component Object Model (COM) object that is contained in another component, such as an ActiveX control in the context of an HTML page. This parameter represents the outermost IUnknown of the calling component. The function attempts the download in the context of the ActiveX client framework, and allows the caller container to receive callbacks on the progress of the download. szURL A pointer to a string value that contains the URL to download. Cannot be set to NULL. If the URL is invalid, INET_E_DOWNLOAD_FAILURE is returned. szFileName A pointer to a string value containing the name or full path of the file to create for the download. If szFileName includes a path, the target directory must already exist. dwReserved Reserved. Must be set to 0. lpfnCB A pointer to the IBindStatusCallback interface of the caller. By using OnProgress, a caller can receive download status. URLDownloadToFile calls the OnProgress and OnDataAvailable methods as data is received. The download operation can be canceled by returning E_ABORT from any callback. This parameter can be set to NULL if status is not required. Return Value Returns one of the following values. S_OK The download started successfully. E_OUTOFMEMORY The buffer length is invalid, or there is insufficient memory to complete the operation. INET_E_DOWNLOAD_FAILURE The specified resource or callback interface was invalid. Remarks URLDownloadToFile binds to a host that supports IBindHost to perform the download. To do this, it first queries the controlling IUnknown passed as pCaller for IServiceProvider, then calls IServiceProvider::QueryService with SID_SBindHost. If pCaller does not support IServiceProvider, IOleObject or IObjectWithSite is used to query the object's host container. If no IBindHost interface is supported, or pCaller is NULL, URLDownloadToFile creates its own bind context to intercept download notifications. URLDownloadToFile returns S_OK even if the file cannot be created and the download is canceled. If the szFileName parameter contains a file path, ensure that the destination directory exists before calling URLDownloadToFile. For best control over the download and its progress, an IBindStatusCallback interface is recommended.
Voce pode tratar o resultado do UrlDownloadToFile UrlDownloadToFile(nil, PChar(sSource1), PChar(sDest1), 0, nil) = 0; alguns exemplos:
procedure TForm1.Button1Click(Sender: TObject);
var
 savedlg: TSaveDialog;
begin
savedlg := TSaveDialog.Create(Self);

if savedlg.Execute then
 if DownloadFile(Edit1.Text, savedlg.FileName) then
   MessageBox(Application.Handle, 'Download efetuado com sucesso', 'Informação', MB_ICONINFORMATION)
 else
   MessageBox(Application.Handle, 'Download falhou', 'Informação', MB_ICONEXCLAMATION);
end;

function TForm1.DownloadFile(Source, Dest: string): Boolean;
begin
try
  Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
except
  Result := False;
end;

end;
outro exemplo:
uses UrlMon

function DownloadFile(Source, Dest: string): Boolean; 
begin 
  try 
    Result :=  UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0; 
  except 
    Result := False; 
  end; 
end; 

procedure TForm1.Button1Click(Sender: TObject); 
begin 
  if DownloadFile  ('http://www.delphi3000.com/index.htm, 'c:\index.htm') then 
   ShowMessage('Download successful') 
  else 
   ShowMessage('Download unsuccessful') 
end;

outros exemplos:

http://www.devmedia.com.br/articles/viewcomp.asp?comp=306

http://www.swissdelphicenter.ch/torry/showcode.php?id=412

abraço e feliz natal

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      651,9k
×
×
  • Criar Novo...