小弟正在開發一個簡單網頁給員工上傳/更改檔名/刪除/下載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();
}
}
你可以試試改一下程式碼的順序
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();
}
}