2014-10-04 87 views
2

我的根目錄中有一個名爲files的文件夾。 此文件夾包含範圍從1 Kb-1 GB的文件。將文件從服務器下載到客戶端的計算機

我想要一個php腳本,可以簡單地使用AJAX異步下載文件。

此代碼啓動下載腳本點擊一個文件時:

JQUERY

$('.download').click(function(){ 
    var src =$(this).attr('src'); 
    $.post('download.php',{ 
     src : src //contains name of file 
    },function(data){ 
     alert('Downloaded!'); 
    }); 
}); 

PHP

<?php 
    $path = 'files/'.$_POST['src']; 
    //here the download script must go! 
?> 

這將是最好,最快,安全下載文件的方式?

+0

- 爲什麼?你需要做什麼不能通過讓服務器管理它來完成?爲什麼你需要涉及Ajax? – Quentin 2014-10-06 06:12:28

回答

3
<?php 
/** 
* download.php 
*/ 

if (!empty($_GET['file'])) { 
    // Security, down allow to pass ANY PATH in your server 
    $fileName = basename($_GET['file']); 
} else { 
    return; 
} 

$filePath = '???/files/' . $fileName; 
if (!file_exists($filePath)) { 
    return; 
} 

header("Content-disposition: attachment; filename=" . $fileName); 
header("Content-type: application/pdf"); 
readfile($filePath); 

而實際上AJAX請求使用Content-disposition: attachment時是不必要的,「我想一個PHP腳本,可以異步使用AJAX只需下載一個文件」

<a href="download.php?file=file1.pdf">File1</a> 
+1

如果我不知道「內容類型」,該怎麼辦? – 2014-10-04 13:27:42

+1

只是不使用它時。它有助於瀏覽器確定文件打開程序(電影,圖像,MS字等) – 2014-10-04 13:41:00

+0

您不能使用Content-Type。除非您重寫,否則PHP將默認聲明它是一個HTML文檔。 – Quentin 2014-10-06 06:12:58

相關問題