2011-12-06 27 views
0

有沒有一種快速內聯的方式,使第一次初始點擊後,我的一些鏈接提示'保存文件爲'(與右鍵點擊相同的屏幕)?簡單的方法來使鏈接提示「另存爲」

+0

可能重複的[用php打開下載對話框](http://stackoverflow.com/questions/985083/open-download-dialog-with-php) – mario

+0

不是重複的,因爲這個問題並沒有直接詢問如何使用服務器端來完成它。因此,答案需要解釋它不能在客戶端完成,因此需要服務器端方法。 – Gajus

回答

2

您只需發送適當的標題即可。 Content-Disposition是關鍵(參見http://en.wikipedia.org/wiki/MIME)。

請參閱下面的PHP示例。

/** 
* @author Gajus Kuizinas <[email protected]> 
* @copyright Anuary Ltd, http://anuary.com 
* @version 1.0.1 (2011 11 18) 
*/ 
function ay_file_force_download($file, $file_name = NULL) 
{ 
    if(headers_sent()) 
    { 
     throw new Ay_Exception('Headers have been already sent. Cannot force file download.'); 
    } 

    $file_name = $file_name === NULL ? basename($file) : $file_name; 

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename=' . $file_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($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 

    exit; 
} 
+0

哦 - 但是,這不適用於我所有的鏈接嗎?我只是想用某些鏈接來做到這一點? - 可能嗎? –

0

你真的需要在PHP端什麼是設置Content-Disposition頭,依戀,如header('Content-Disposition: attachment; filename=name-of-file');。如果您必須或希望在客戶端執行此操作,瀏覽器將自動嘗試下載大量文檔類型,因此您只需提供一個直接鏈接即可。顯然這並不是爲了你而發生的,但是,當然這不是可靠的。

相關問題