2014-06-11 2 views
0

url에서 내 서버로 zip 파일을 다운로드해야하는데 이는 동적으로 생성되므로 URL에 확장자가 없음을 의미합니다. zip 파일은 URL에 의해 생성됩니다. 우리는 그 zip 파일을 서버에 저장해야합니다.동적으로 생성 된 url에서 서버로 파일을 다운로드하십시오.

나는 이것을 시도했다.

function DownloadFile($reportDownloadUrl, $downloadPath) { 
    $reader = fopen(urldecode($reportDownloadUrl), 'rb') or die("url cannot open"); 
    if (!file_exists($downloadPath)) { 
      die('File does not exist'); 
    } 
    $writer = fopen($downloadPath, 'wb') or die("cannot open file"); 
    if (!$reader) { 
     throw new Exception("Failed to open URL " . $reportDownloadUrl . "."); 
    } 
    if (!$writer) { 
     fclose($reader); 
     throw new Exception("Failed to create ZIP file " . $downloadPath . "."); 
    } 
    $bufferSize = 10 * 1024; 
    while (!feof($reader)) { 
     if (false === ($buffer = fread($reader, $bufferSize))) { 
      fclose($reader); 
      fclose($writer); 
      throw new Exception("Read operation from URL failed."); 
     } 
     if (fwrite($writer, $buffer) === false) { 
      fclose($reader); 
      fclose($writer); 
      $exception = new Exception("Write operation to ZIP file failed."); 
     } 
    } 
    fclose($reader); 
    fflush($writer); 
    fclose($writer); 
} 

이것을 사용하면 확장자가 .zip 인 파일을 다운로드 할 수 있지만 확장자가없는 파일은 다운로드 할 수 없습니다. 나는 이것을 알아 내기 위해 나이를 먹으려 고 노력 해왔다. 방법이 있어야한다. 어떤 제안이라도 대단히 감사한다.

미리 감사드립니다.

답변

0

확장명이없는 URL을 코드와 함께 다운로드 할 수없는 몇 가지 이유가있을 수 있습니다. 코드가 직접 링크에서 읽도록 설계되었지만 특정 쿠키, 사용자 에이전트, 리퍼러 등을 보내지 않으면 파일이 직접 액세스 할 수없는 경우가 있습니다.

그 이유는 당신이 cURL library을 들여다 볼 것을 권장합니다. 앞에서 설명한 모든 작업을 쉽게 수행 할 수있는 기능 세트를 제공합니다.

function DownloadFile($reportDownloadUrl, $downloadPath) { 
{ 
    $ch = curl_init($reportDownloadUrl); 
    $fh = fopen($downloadPath, 'ab'); 
    if($fh === false) 
     throw new Exception('Failed to open ' . $downloadPath); 

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_FILE, $fh); // file handle to write to 

    $result = curl_exec($ch); 
    if($result === false) // it's important to check the contents of curl_error if the request fails 
     throw new Exception('Unable to perform the request : ' . curl_error($ch)); 
} 

컬 등, 프록시를 사용하여 데이터를 업로드, 파일 다운로드를 다시 시작 당신은 모든 약 읽을 수 같은 멋진 많은 옵션이 포함되어 여기 DownloadFile 기능을 모방 한 조각은 리디렉션을 다음 것을 제외입니다 코드에 대한 http://php.net/curl-setopt

몇 가지 더 : 설명서의 그것 (! $ 작가) 검사가 중복 된 경우

  • 는 경우 (! $ 리더)하고 스크립트가합니다 (fopen을 경우 죽을 것이기 때문에) 호출 실패
  • $ 예외를 던지지 않았습니다.
관련 문제