php檔案下載

來源:互聯網
上載者:User

標籤:style   io   ar   color   os   使用   sp   檔案   on   

近些日子,老被這個檔案下載所苦惱,搞了幾天,終於解決,特此把過程詳解於下:

   1.在下載檔案之前,首先應當判斷檔案是否存在;

   2.當檔案存在的情況下,設定檔案檔案輸出的格式,需要四項設定,分別如下:

                                   header("content-type:image/jpg");  //設定下載檔案類型,這裡假設下載的檔案jpg檔案

                                  header("Accept-Ranges:bytes");   //告訴用戶端瀏覽器返回的檔案大小是按照位元組進行計算的

                                header("Accept-Length:".filesize("$filePath"));  // 告訴瀏覽器返回的檔案大小,$filePath表示要下載的檔案的路徑

                                header(‘content-disposition:attachment;filename=1.jpg‘); //說明輸出的是一個附件同時告訴檔案名稱,切記filename後面只能用相對路徑或者直接使用檔案名稱,不能使用變數代替,否則會出錯

3.讀取要下載的檔案:例如用readfile()函數讀取上面的圖片檔案,或者寫一個迴圈語句按照一定的程式讀取;

例如代碼:

                         <?php
//下載檔案成功解決
header("content-type:text/html;charset=utf-8");
$filePath = "image/1.jpg";  //這裡設定下載的檔案路徑
if(file_exists($filePath)){


    //設定檔案下載需要的頭
header("content-type:image/jpg");
header("Accept-Ranges:bytes");
header("Accept-Length:".filesize("$filePath"));
header(‘content-disposition:attachment;filename=1.jpg‘); //但是這裡filename後面只能使用檔案名稱
//readfile("image/1.jpg");  或者用下面的方式
    $fopen = fopen($filePath,"rb");
    $buffer = 1024;
    $fcon =0;
    while(!feof($fopen) and $fcon <= filesize("$filePath")){
        $fileCon = fread($fopen,$buffer);
        $fcon += $buffer;
        echo $fileCon;
        }
    fclose($fopen);
    }
else echo "您要下載的檔案不存在";


?>     

php檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.