简体   繁体   中英

How to display pdf from db in iframe

I made a file upload system where the files when uploaded is stored in a db. now i have created an iframe so that i can view the files inside it. currently i have set the iframe to display a file(not inside db) but when i`m unable to set the iframe to display the files from the db. I've done a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks! 选中打开的PDF按钮后,PDF必须在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');
?>

Try making a full URL out of the src path, and don't include any spaces in the path. So, something like this:

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

I've just been playing around with manipulating an iframe this way, and it seems to work.

I know you said you are getting these PDFs from a DB, that you aren't trying to load a specific file, but for this to work with an iframe it would be best if your server would serve up the contents of each PDF from a specific URL.


OK, so, based on your comments below, you could use a link like this:

<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>

Then modify openPdf() like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM