javascript - 如何在 iframe 中显示 db 中的 pdf

标签 javascript php jquery html mysql

我制作了一个文件上传系统,上传的文件存储在数据库中。现在我创建了一个 iframe,以便我可以查看其中的文件。目前我已将 iframe 设置为显示文件(不在数据库内),但是当我无法设置 iframe 以显示数据库中的文件时。我对此做了很多研究,但遇到了一个又一个的障碍,所以我真的希望你能在这方面提供帮助,非常感谢! 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>
<小时/>

下载.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');
?>

最佳答案

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

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

我刚刚尝试过以这种方式操作 iframe,而且它似乎有效。

我知道您说过您是从数据库获取这些 PDF,您并没有尝试加载特定文件,但是为了使其能够与 iframe 一起使用,最好您的服务器能够提供每个文件的内容来自特定 URL 的 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;
}

关于javascript - 如何在 iframe 中显示 db 中的 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247965/

相关文章:

javascript - 试图理解回调函数

javascript - 与我的 jquery 弹出窗口和自动调整文本区域大小发生冲突

javascript - 如何在ajax中引用文本字段名称?

javascript - 无法将值绑定(bind)到 ng-model 以在事件中选择选项

javascript - 如何检查标签是否有任何文本

javascript - 如何在firebase上执行sql "LIKE"操作?

javascript - 是否可以创建一个在 Javascript 中调用时表现得像函数的对象?

php - 我应该使用用户的 md5 密码通过电子邮件验证他的帐户吗?

php 正则表达式匹配可能的重音字符

php - 如何通过 PHP 访问 RESTful API