我想下載 php 中的圖像文件。<?phpif(isset($_REQUEST["file"])){ $filepath = BASE_URL.'assets/uploads/save_template_images/template1_221594899972.png'; // Process download if(file_exists($filepath)) { echo $filepath; exit; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($filepath).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($filepath)); flush(); // Flush system output buffer readfile($filepath); die(); } else { echo $filepath; exit; http_response_code(404); die(); }} ?>在我的索引頁面中,我有一個錨標記,如果單擊錨標記,則運行上面的代碼。我沒有顯示錨標記,因為我將$filepath靜態值放在上面的代碼中。當我運行上面的代碼時,它會進入其他條件。我認為,上面的代碼沒有采用項目的完整路徑。如果我將圖像放在同一文件夾中,則會下載。
1 回答

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
首先確保文件allow_url_fopen中的設置php.ini已打開。之后使用此代碼下載您的文件:
<?php
$url = 'https://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg';
$file = './files/'.basename($url);
file_put_contents($file, file_get_contents($url));
?>
為了成功下載,文件目錄必須存在。但我認為添加目錄存在檢查效率很低,因為我認為您已經知道在哪里保存正在下載的文件。
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消