php上传pdf文件及读取其内容

原项目地址:https://gitee.com/chenhr_230/PHP-read-PDF

upload.php:

<?php

header("content-type:text/html;charset=utf-8");
// 上传PDF
if($_FILES["file"]["type"] == "application/pdf" && $_FILES["file"]["size"] < 5*1024*1024){ //判断文件类型和文件的大小
    if($_FILES["file"]["error"]){
        header('Refresh:3,Url=index.html');
        echo "上传文件出现错误<br />";
        echo "3s后跳转";
    }else{
        if(file_exists("upload/".$_FILES["file"]["name"])){ //判断文件是否存在
            header('Refresh:3,Url=index.html');
            echo "文件已存在<br />";
            echo "3s后跳转";
        }else{
            $path = $_FILES['file']['name'];
            $pathinfo = pathinfo($path);
            $typename = $pathinfo['extension']; // 文件的扩展名
            $filename = time().".".$typename;
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$filename); // 上传文件
            echo "文件上传成功:" . "upload/" . $_FILES["file"]["name"];
            $file_path = "upload/".$filename; // 文件路径
            header("Location:read_pdf.php?filename=$file_path");
        }
    }
}else{
    header("Refresh:3,Url=index.html");
    echo "上传文件不符合类型<br />";
    echo "3s后跳转";
}
?>

read_pdf.php:

<?php
$file = $_GET['filename'];
// 检测文件格式,检测文件是否存在
if(strtolower(substr(strrchr($file,'.'),1)) != 'pdf'){
    echo "文件格式不正确";
    exit();
}
if(!file_exists($file)){
    echo "文件不存在";
    exit();
}
header('Content-type: application/pdf');
$fp = fopen($file, "r"); // 打开文件

fpassthru($fp); // 读取pdf中的内容

fclose($fp);
?>

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>pdf读取测试</title>
    <link rel="stylesheet" href="css/index.css" />
</head>
<body>
    <div class="form">
       <form action="upload.php" method="post" enctype="multipart/form-data">
            <label for="file">选择上传的文件:&nbsp;&nbsp;&nbsp;&nbsp;</label>
            <input type="file" name="file" id="file" />
            <br />
            <input type="submit" value="提交" id="sub" />
        </form> 
    </div>
    
</body>
</html>

测试:
将readPDF项目文件复制到phpEnv\www\localhost路径下,运行phpEnv,打开浏览器访问localhost/readPDF/index.html。

猜你喜欢

转载自blog.csdn.net/username666/article/details/106948454