微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

可从数据库下载的 PDF

如何解决可从数据库下载的 PDF

我有一个存储文档文件名的数据库表,在本地电脑上我有一个名为 uploads文件夹,用于存储用户上传的实际文件

上传文件的方式如下,

$filename = $_FILES['attachment']['name'];
    
    // destination of the file on the server
    $destination = 'uploads/' . $filename;
    
    // get the file extension
    $extension = pathinfo($filename,PATHINFO_EXTENSION);
    
    // the physical file on a temporary uploads directory on the server
    $file = $_FILES['attachment']['tmp_name'];
    $size = $_FILES['attachment']['size'];
    
    if (!in_array($extension,['zip','pdf','docx'])) {
      echo "You file extension must be .zip,.pdf or .docx";
    } elseif ($_FILES['attachment']['size'] > 1000000) { // file shouldn't be larger than 1Megabyte
      echo "File too large!";
    } else {
      // move the uploaded (temporary) file to the specified destination
      if (move_uploaded_file($file,$destination)) {
        
        $sender_name = $_POST['sender_name'];
        $contact = $_POST['contactnumber'];
        $sender_mail = $_POST['sender_email'];
        $description = $_POST['description'];
        $applied = date('Y-m-d');
        
        $jobapply = "INSERT INTO `job_submission`(`NAME`,`CONTACT`,`EMAIL`,`MESSAGE`,`APPLIED_ON`,`CAREER_ID`,`CV`) VALUES 
 ('$sender_name','$contact','$sender_mail','$description','$applied','$idc','$filename')";
        
        if (MysqLi_query($connect,$jobapply)) {
          echo "You Application Was Submitted Successfully! We Wish You All The Best";
        }
      } else {
        echo "Failed to upload file.";
      }
    }

这段代码的结果是文件名和其他数据一起存储在数据库中,另一方面文件也存储在上传目录中。

Database Data

Local PC

现在我想使用按钮将文件夹中存储的文件下载到机器上。为此,我编写了如下代码

 if (isset($_GET['file_id'])) {
 $id = $_GET['file_id'];
 // fetch file to download from database
 $sql = "SELECT * FROM job_submission WHERE JOB_ID='$id'";
 $result = MysqLi_query($connect,$sql);
 $file = MysqLi_fetch_assoc($result);
 $filepath = 'uploads/' . $file['CV'];
 if (file_exists($filepath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-disposition: attachment; filename=' . basename($filepath));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize('uploads/' . $file['CV']));
    readfile('uploads/' . $file['CV']);
    exit;
}
}

上面的代码是从表格中的一个按钮调用的,

<td><a href="careers.PHP?file_id=<?PHP echo $rowselect['JOB_ID'] ?>">Download</a> </td>

文件被下载但它没有打开并抛出一个错误

错误无法加载 PDF 文档。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。