如何在iframe中显示来自db的pdf

时间:2018-03-13 03:40:47

标签: javascript php jquery html mysql

我制作了一个文件上传系统,其中上传的文件存储在数据库中。现在我已经创建了一个iframe,以便我可以查看其中的文件。目前我已将iframe设置为显示文件(不在db内),但是当我无法设置iframe来显示db中的文件时。我已经做了很多关于此的研究,但在路障之后遇到了障碍,所以我非常希望你能帮助我,非常感谢! WHEN THE OPEN PDF BUTTON IS CLICKED THE PDF MUST OPEN IN THE IFRAME

    <html>
<title>File|Mgr</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
<link href="globe.png" rel="shortcut icon">
<?php
date_default_timezone_set("Asia/Calcutta");
//echo date_default_timezone_get();
?>


<?php
   $conn = mysqli_connect("localhost","root","","stu_supervision");
 session_start();
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

if(isset($_POST['submit'])!="")
{
  $name=$_FILES['photo']['name'];
  $size=$_FILES['photo']['size'];
  $type=$_FILES['photo']['type'];
  $temp=$_FILES['photo']['tmp_name'];
  $date = date('Y-m-d H:i:s');
  //$caption1=$_POST['caption'];
 // $link=$_POST['link'];
  $file_error = $_FILES['photo']['error'];


    $file_ext = explode('.', $name);
    $file_ext = strtolower(end($file_ext));

    //$allowed  = array('jpg', 'jpeg');
    $allowed  = array('pdf');

    if(in_array($file_ext, $allowed))
    {
        if($file_error === 0)
        {
             if(file_exists('par_files/' . $name))
                {
                   // die('<script type="text/javascript">alert("File with that name already exists.");location.replace("index.php")</script>');   

                   die('<script type="text/javascript">alert("File with that name already exists.");location.replace("par_upload.php")</script>');   
                }


            //if($size <= 2097152) {




    //--------WHEN UPLOADING FILE, A UNIQUE ID IS GENERATED IN FILES FOLDER THRU 1ST METHOD -------------------
               /// $file_name_new = uniqid('', true) . '.' . $file_ext; 
              //  $file_destination = 'files/' . $file_name_new;  
                $file_destination = 'par_files/'.$name ;
                move_uploaded_file($temp, $file_destination);

                $query=mysqli_query($conn,"INSERT INTO upload (name,date,par_id) VALUES ('$name','$date','".$_SESSION['par_id']."')");


                if($query){
               // header("location:index.php");
                    header("location:par_upload.php");
                }
                else{
                die(mysql_error());
                }
    }

        }
     else
      { 
        echo '<script language="javascript">';
        echo 'alert(" SORRY! YOU ARE ONLY ABLE TO UPLOAD PDF FILES")';
        echo '</script>';
      }
}

?>





<html>
<body>

<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="screen">
<link rel="stylesheet" type="text/css" href="css/DT_bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="font-awesome/css/font-awesome.min.css"/>
</head>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>

<script type="text/javascript" charset="utf-8" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" language="javascript" src="js/DT_bootstrap.js"></script>
<?php include('dbcon.php'); ?>
<style>
.table tr th{

    border:#eee 1px solid;

    position:relative;
    #font-family:"Times New Roman", Times, serif;
    font-size:12px;
    text-transform:uppercase;
    }
    table tr td{

    border:#eee 1px solid;
    color:#000;
    position:relative;
    #font-family:"Times New Roman", Times, serif;
    font-size:12px;

    text-transform:uppercase;
    }

#wb_Form1
{
   background-color: #00BFFF;
   border: 0px #000 solid;

}
#photo
{
   border: 1px #A9A9A9 solid;
   background-color: #00BFFF;
   color: #fff;
   font-family:Arial;
   font-size: 20px;
}
    </style>
                        <a title="par home page" href="http://localhost/PROJ/par_welcome.php" class="btn btn-warning">par homepage</a> <br><br>
                            <table cellpadding="0" cellspacing="0" border="0" class="table table-bordered">     
            <tr><td><form enctype="multipart/form-data"  action="" id="wb_Form1" name="form" method="post">     
                    <input type="file" name="photo" id="photo" accept="application/pdf"  required="required"></td>



                    <td><input type="submit" class="btn btn-danger" value="SUBMIT" name="submit">
            </form> <strong>SUBMIT HERE</strong></tr></td></table>
                 <div class="col-md-18">
    <div class="container-fluid" style="margin-top:0px;">
   <div class = "row">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="table-responsive">


                        <form method="post" action="delete.php" >
                     <table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">

                            <thead>

                                <tr>

                                    <th>ID</th>
                                    <th>FILE NAME</th>
                                   <th>Date</th>
                                    <th>username</th>

                    <th>Download</th>   
                        <th>view</th>


                                </tr>
                            </thead>
                            <tbody>

                        <?php 
                            $query=mysqli_query($conn, "select * from `upload` left join `par` on par.par_id=upload.par_id where par.par_id= '".$_SESSION['par_id']."' ORDER BY id DESC ");

                               // $query=mysqli_query($conn, "select * from `upload` left join `par` on par.par_id=upload.par_id where p_username = '".$_SESSION['par_id']."' ORDER BY id DESC ");
                                if($query === false){
    throw new Exception(mysql_error($conn));
}
                            while($row=mysqli_fetch_array($query)){
                            $id=$row['id'];
                            $name=$row['name'];
                            $date=$row['date'];
                            $username = $row['p_username'];
                            ?>
                                        <tr>

                                         <td><?php echo $row['id'] ?></td>
                                         <td><?php echo $row['name'] ?></td>
                                         <td><?php echo $row['date'] ?></td>
                                             <td> <?php echo $row['p_username'] ?></td>
    <td>
            <!--    <a href="download.php?filename=<?php // echo $name;?>" title="click to download">VIEW <!--<span class="glyphicon glyphicon-paperclip" style="font-size:20px; color:blue"></span> -->
                <!--    </a> --> 
                 <input type="button" value="Open PDF" onclick = "openPdf()"/>
     </td>
                 <td>
                   <iframe id="myFrame" style="display:none" width="600" height="300"></iframe>
                 </td>  




                                </tr>

                                  <?php }
                                ?>
                            </tbody>
                        </table>
                           </div>

</form>
                                                        <!--*******************************************-->
                                                        <script>
                                                        function openPdf()
                                        {
                                        var omyFrame = document.getElementById("myFrame");
                                        omyFrame.style.display="block";
                                        omyFrame.src = "PRICE LIST.pdf";
                                        }
                                                        </script>
                                                        <!--**************************************-->
      </div>
        </div>
        </div>
    </div>



</body>
</html>

的download.php

    <?php
function output_file($file, $name, $mime_type='')
{
//if(!is_readable($file)) die('<script type="text/javascript">alert("File not found!");location.replace("index.php")
    if(!is_readable($file)) die('<script type="text/javascript">alert("File not found!");location.replace("par_upload.php")
    </script>');

$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};

@ob_end_clean();


if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');



   // header('Content-Type: ' . $mime_type);
    header('Content-type: application/pdf');

header('Content-Disposition: inline; filename="'.$name.'"');
//header('Content-Disposition: attachment; filename="'.$name.'"');


header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 2017 05:00:00 GMT");
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
$chunksize = 1*(1024*1024);
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);

while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
print($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else

die('Error - cannot open file.');
die();
}
set_time_limit(0);
$file_path='par_files/'.$_REQUEST['filename'];
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>

1 个答案:

答案 0 :(得分:1)

尝试从src路径中创建完整的URL,并且不要在路径中包含任何空格。所以,像这样:

omyFrame.src = "http://example.com/pdfs/PRICE%20LIST.pdf";

我一直在玩这种方式操纵iframe,它似乎有效。

我知道你说你从数据库中获取这些PDF,你不是要加载一个特定的文件,但为了使用iframe,最好是服务器提供每个文件的内容。来自特定网址的PDF。

好的,基于您下面的评论,您可以使用以下链接:

<a href="javascript:void(0)"
  onclick="openPdf('download.php?filename=<?php echo $name;?>')"
  title="click to download">VIEW <span class="glyphicon glyphicon-paperclip"
  style="font-size:20px; color:blue"></span>
</a>

然后像这样修改openPdf()

function openPdf(src)
{
  var omyFrame = document.getElementById("myFrame");
  omyFrame.style.display="block";
  omyFrame.src = src;
}