问题描述
我试图在我的网站上强制下载 pdf 文件。文件已成功下载,但在单击下载时会在同一文件夹中创建一个随机名称的空文件。我在文件夹中有多个空文件。
下载.PHP :
<?PHP
$file = $_GET['file'];
header('Content-type: application/pdf');
header('Content-Length: ' . filesize($file));
header('Content-disposition: attachment; filename="'.$file.'"');
?>
解决方法
假设您将 pdf 存储在数据库中。
<div class="wrapper">
<div class="jumbotron">
<h1 class="display-4">The Truth Is Out There</h1>
</div>
<div class="container-fluid">
<div class="row">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
<form class="bg-dark">
<p>Filter Search</p>
<ul class="list-group bg-dark">
<li class="list-group-item bg-dark">
<label for="date">Enter Date</label>
<input type="text" placeholder="1/10/2010" id="datetime" />
</li>
<li class="list-group-item bg-dark">
<label for="city">Enter a City</label>
<input type="text" placeholder="roswell" id="city">
</li>
<li class="list-group-item bg-dark">
<label for="state">Enter a State</label>
<input type="text" placeholder="ca" id="state">
</li>
<li class="list-group-item bg-dark">
<label for="Country">Enter a Country</label>
<input type="text" placeholder="us" id="country">
</li>
<li class="list-group-item bg-dark">
<label for="Shape">Enter a Shape</label>
<input type="text" placeholder="crcle" id="shape">
</li>
<li class="list-group-item bg-dark">
<button id="filter-btn" type="button" class="btn btn-dark">Clear Table</button>
</li>
</ul>
</form>
</div>
<div class="col-md-9">
<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Shape</th>
<th>Duration</th>
<th>Comments</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
请注意,如果您在此之前发送了一些标题,它将无法正常工作。
确保您正确创建了 pdf 文件。
//you need to decode
$decoded = base64_decode($downloaded->pdf);
//name of pdf
$filename =date('Ymdhis').'.pdf';
$size=strlen($decoded);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.($filename).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header("Cache-Control: no-cache,must-revalidate");
header("Pragma: no-cache");
header('Content-Length:'.$size);
echo($decoded);
exit;