2013-06-05 25 views
-1

下面的代碼強制瀏覽器發出提示保存/打開文件(https://kb.wisc.edu/images/group27/13334/open-prompt.PNG),即使它是一個圖像或PDF文件。php如何提供文件,但不能下載

我想讓圖像像往常一樣打開,pdf文件要在瀏覽器中顯示。當然其他不受瀏覽器支持的文件如zip,rar,doc,xls等將激發保存文件對話框。

編輯: 我的目的不是阻止客戶端保存文件,當然他們可以保存它是不可能的。我想讓服務讓圖像像PHP這樣的文件,如main.php?file = randomcode(存儲在數據庫中),而不是/images/somefilename.jpg。我的代碼強制客戶端下載它,但我想顯示它。

header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private", false); 
header("Content-Type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"" . $filename . "." . $fileinfo["file_extension"] . "\";"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: " . filesize($file)); 
$fp = fopen($file, "r"); 
if ($fp) { 
    while (!feof($fp)) { 
     $cur_data = fread($fp, 1024); 
     echo $cur_data; 
    } 
} else { 
    echo "Error: Could not the read file."; 
} 
+0

你曾經在互聯網上放過的每件東西都會下載,如果它到達網絡瀏覽器的話。你的**實際**問題是什麼? – Amelia

+0

這段代碼強制瀏覽器發出提示保存/打開文件(https://kb.wisc.edu/images/group27/13334/open-prompt.PNG),即使它是圖像或pdf(當然這需要Adobe Reader插入)。我想要像往常一樣打開圖像,在瀏覽器中顯示pdf文件。當然其他不受瀏覽器支持的文件如zip,rar,doc,xls等將激發保存文件對話框。 – Ergec

回答

-1

如果內容類型設置爲八進制流,那麼它將非法傳輸文件意味着用戶將強制下載它。你必須相應地設置內容類型在瀏覽器

將其打開,例如,如果類型是圖像然後

header("Content-Type: image/jpg"); 
header("Content-Type: image/png"); 

,如果它的圖像或pdf然後取出內容處置:頭

0

好吧,顯然你知道文件擴展名,所以你可以這樣做:

if(in_array($fileinfo["file_extension"], array('jpg', 'png', 'gif')) { 

    // set header for viewing the image 

    $mime_type = $fileinfo["file_extension"]; 
    if($mime_type == 'jpg') { 
     $mime_type = 'jpeg'; 
    } 

    header('Content-Type: image/' . $mime_type); 

} 
else { 
    // set headers for downloading the file 
} 
+0

你能否給我舉例說明標題讓我說jpg – Ergec

+0

看到更新的答案 – rednaw

+0

JPEG文件的MIME類型是image/jpeg,而不是image/jpg。 – PleaseStand

0

最終還是由客戶端如何處理它接收到的內容。有一兩件事你可以做的就是擺脫Content-disposition頭的:

header("Content-Disposition: attachment; filename=\"" . $filename . "." . $fileinfo["file_extension"] . "\";"); 

(或者至少獲得有條件擺脫它,根據有關文件的具體因素。)這是什麼頭的作用是告訴客戶端的內容被返回是一個「文件」(你甚至提供了一個文件的建議名稱),應該這樣對待。 HTTP沒有「文件」的本地概念,所以這個頭文件專門用於標識某些「文件」。

通過不提供該標題,您不會向客戶建議該內容是文件。客戶可能仍然推斷它是一個文件,並將其視爲(您無法控制的),但從您的最終,您所做的只是返回內容本身。