可从数据库下载的 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 (将#修改为@)