2013-12-13 101 views
0

我試圖查看存儲在數據庫中的瀏覽器上的文件(即:excel表/ pdf /圖像)。在瀏覽器中使用php查看存儲在數據庫中的文件

我已經寫了一個從數據庫中下載文件的代碼,它正在工作,但我想在瀏覽器中顯示它。

下面是代碼:

<?php require_once('Connections/databasestudents.php'); ?> 
<?php 
    $id = $_GET['id']; // ID of entry you wish to view. To use this enter "view.php?id=x" where x is the entry you wish to view. 

    $query = "SELECT fileContent, filetype FROM file where id = $id"; //Find the file, pull the filecontents and the filetype 
    $result = MYSQL_QUERY($query); // run the query 

    if($row=mysql_fetch_row($result)) // pull the first row of the result into an array(there will only be one) 
    { 
     $data = $row[0]; // First bit is the data 
     $type = $row[1]; // second is the filename 

     Header("Content-type: $type"); // Send the header of the approptiate file type, if it's' a image you want it to show as one :) 
     print $data; // Send the data. 
    } 
    else // the id was invalid 
    { 
     echo "invalid id"; 
    } 
?> 

什麼情況是,view.php下載並沒有什麼看。

有什麼建議嗎?

+0

PHP是在您的網絡服務器上配置不正確,或者未安裝。 – Sammitch

+0

我所有的其他php頁面都可以工作!並且我下載了wamp服務器,它自動安裝了php,sql和apache – HaneenSu

回答

0

根據你的代碼,$row[1]是「文件名」。內容類型頭應包含內容類型代替,即:該文件的MIME類型,例如:

header('Content-type: application/pdf'); 

如果你想添加一個文件名:

header('Content-type: application/pdf'); 
header('Content-Disposition: attachment; filename='.$row[1]); 
print $data; 

確保$data是內容例如,該文件可以從readfile()中獲取。

瞭解更多關於該手冊:http://php.net/manual/en/function.readfile.php

請記住,雖然PDF和圖像易於查看通過瀏覽器,我認爲Excel中需要一些特設插件這一點。

一個更完整的例子右出手動的,讓你更徹底的瞭解(並非所有的標題是必要的,你應該相應改變別人對你的代碼):

header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename='.basename($file)); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($file)); 

ob_clean(); 
flush(); 
readfile($file); 

exit; 
+0

謝謝..它現在不下載,它會打開一個新頁面。但是,出現錯誤和出現很多奇怪的字符 – HaneenSu

+0

這是因爲代碼解釋方式有問題,所以顯示的是二進制文件內容。閱讀鏈接手冊頁面上的更多信息,獲取您的特定案例所需的所有標題 –

相關問題