프로그래밍/델파이

URLOpenBlockingStream을 이용하여 스트림으로 다운로드 받기

채윤아빠 2008. 8. 7. 11:16
728x90
반응형
URLMon 유닛에 보면, URLOpenBlockingStream 함수가 있습니다.
이 함수를 이용하면 인터넷에 있는 파일을 URL로 스트림으로 다운로드 받을 수 있습니다.

아래와 같은 코드를 참고하여 작성하면 되겠습니다.

procedure TForm1.btnDownloadClick(Sender:TObject);
var
  hRet: HRESULT;
  AMemoryStream : TMemoryStream;
  AStream: IStream;
  AStatStg: TStatStg;
  nRead:int64;
begin
  AMemoryStream := TMemoryStream.Create;
  try
    hRet := URLOpenBlockingStream(nil, PChar(ieaURL.Text), AStream, 0, self);
    if (hRet <> S_OK) then
      exit;

    if (AStream.Stat(AStatStg, STATFLAG_NONAME) = S_OK) then
    begin
      if (AStatStg.cbSize > 0) then // 실제로 스트림에 저장된 데이터가 있는가?
      begin
        AMemoryStream.SetSize(AStatStg.cbSize); // 복사할 메모리 할당

        if (AStream.Read(AMemoryStream.Memory, AStatStg.cbSize, @nRead) = S_OK) then
          ; // 성공적으로 다운로드 완료 후 처리해야할 작업
      end;
    end;
    AStream := nil; // 사용을 마친 IStream 인터페이스 소멸
  finally
    AMemoryStream.Free;
  end;


URLOpenBlockingStream 에서 주의할 점은 세 번째 파라미터로 넘겨주는 IStream 변수는 그 함수 내부에서 생성해서 반환되어 나온다는 점입니다. 반환된 스트림에 URL에서 다운로드 받은 내용이 들어 있으니, 위 예제 코드와 같이 그대로 이용하면 됩니다.

참고자료 : http://msdn.microsoft.com/en-us/library/ms775127(VS.85).aspx