2016-12-26 65 views
0

我已經試過各種代碼,我發現,但沒有奏效,我下載的文件...PHP:從服務器

當我使用的ReadFile()或fopen()或者是這樣的:

function makeDownload($file, $dir, $type) { 

header("Content-Type: $type"); 

header("Content-Disposition: attachment; filename=\"$file\""); 

readfile($dir.$file); 

} 

...下載被啓動,但該文件是總是空...

這裏是最後的代碼,我已經試過:

$filename = "gandalf.jpg"; 
// define error message 
$err = '<p style="color:#990000">Sorry, the file you are requesting is unavailable.</p>'; 
if (!$filename) { 
// if variable $filename is NULL or false display the message 
echo " filename NULL"; 
echo $err; 

} else { 
// define the path to your download folder plus assign the file name 
$path = 'upload/'.$filename; 

// check that file exists and is readable 
if (file_exists($path) && is_readable($path)) { 
    echo "file exists"; 
    // get the file size and send the http headers 
    $size = filesize($path); 
    header('Content-Type: image/png'); 
    header('Content-Length: '.$size); 
    header('Content-Disposition: attachment; filename='.$filename); 
    header('Content-Transfer-Encoding: binary'); 
    // open the file in binary read-only mode 
    // display the error message if file can't be opened 

    //readfile($path.$filename); 
    $file = @ fopen($path, 'rb'); 
    if ($file) { 
     // stream the file and exit the script when complete 
     fpassthru($file); 
     exit; 
    } else { 
     echo $err; 
    } 
} else { 
    echo $err; 
} 
} 

這是我的代碼的來源:Source code

我希望你能幫助我:)

我使用谷歌瀏覽器 我需要你爲這個小項目的幫助:Link to Project

當你點擊一個文件在下拉菜單中出現「herunterladen」(德語下載)這裏是我想要啓動php下載代碼的地方

我只需要PHP的最基本的下載功能...爲什麼在w3schools上有一個上傳示例但不是下載示例? OO

+0

它說出你使用的是什麼瀏覽器,以及如何你得到的下載功能是非常重要的。例如,當涉及通過JavaScript觸發下載時,尤其是Safari有一些嚴重的*咳嗽*「安全功能」*咳嗽*。花了整整一天的時間來繞過那一個。 - 雖然這很可能不是你的問題的原因,但它可能仍然會說清楚。 – NoobishPro

+0

刪除'echo「文件存在」;'行 – EhsanT

回答

0
$fileSource= $_GET['fileSource'];  //If you are passing the filename as a URL parameter 
$fileSource= "sample.pdf"  //If the filename is fixed in the current folder 
if($fileSource) { 
    $filesize = filesize($fileSource); 
    $path_parts = pathinfo($fileSource); 
    $ext = strtolower($path_parts["extension"]); 
    switch ($ext) { 
    case "pdf": 
     header("Content-Disposition: attachment; 
     filename=\"".$path_parts["basename"]."\""); // use 'attachment' to 
     force a download 
     header("Content-type: application/pdf"); // add here more headers 
     for diff. extensions 
     break; 
    default: 
    header("Content-type: application/octet-stream"); 
    header("Content-Disposition: filename=\"".$path_parts["basename"]."\""); 
    } 
    if($filesize) { 
     header("Content-length: $filesize"); 
    } 
    readfile($fileSource); 
    exit; 

}