iT邦幫忙

1

PHP 下載 FTP 文件給前端用戶下載

  • 分享至 

  • xImage

小弟正在開發一個簡單網頁給員工上傳/更改檔名/刪除/下載FTP伺服器的文件.
現在上傳/更改檔名/刪除功能可以成功,
但下載部份只能令文件下載到Web伺服器的root directory上,
不能觸發用戶端下載文件, 請問各位大神應如何觸發前端用戶可下載文件?

後端php:

function downloadFile($ftp, $path, $name)
{
    try {
        // 利用ftp_get()成功下載文件到Web伺服器的root directory上
        if ($ftp->get($path,  $name)) {
            // 但不能觸發前端用戶下載文件
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . $name);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($name));

            ob_clean();
            flush();
            readfile($name);

            exit();
        } else {
            echo 'Fail';
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    } finally {
        $ftp->close();
    }
}
黃彥儒 iT邦高手 1 級 ‧ 2023-02-24 16:25:37 檢舉
我記得FTP好像在幾年前被瀏覽器拋棄了,所以解法可能是讓用戶使用超舊的瀏覽器?
player iT邦大師 1 級 ‧ 2023-02-24 16:36:41 檢舉
你要先自己試
PHP跑FTP下載檔案的部分
能否正常工作
如果沒有的話
後續都不用談了

https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
小哈片刻
iT邦研究生 5 級 ‧ 2023-02-25 04:17:56

你可以試試改一下程式碼的順序

function downloadFile($ftp, $path, $name)
{
    try {
        // 利用ftp_get()成功下載文件到Web伺服器的root directory上
        if ($ftp->get($path,  $name)) {
            ob_start(); // 加入這一行
            // 但不能觸發前端用戶下載文件
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . $name);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($name));

            ob_clean();
            ob_end_flush(); // 把flush()改成這個
            readfile($name);

            exit();
        } else {
            echo 'Fail';
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    } finally {
        $ftp->close();
    }
}

我要發表回答

立即登入回答