【问题标题】:how to retrieve file from database in html tags using php如何使用php从html标签中的数据库中检索文件
【发布时间】:2017-09-22 13:28:13
【问题描述】:

大家好,我想像这样使用 php 从 html 标签中的数据库中检索文件

<img src="image/<?php echo $fname?>" alt=" " height="75" width="75">

这是用于图像,但我想用于检索文件,如 .doc、.ppt、.pdf、.txt

我就是这样的

 <a href="file/<?php echo $filename?>"></a>

获取这样的文件

$filename = $row['file'];

检索 .ppt、.pdf、.txt 文件的更好方法是什么?

【问题讨论】:

  • 什么文件?你的代码在哪里?

标签: php html


【解决方案1】:

假设,

  • 您没有使用任何框架
  • 您的视图文件(*.php) 和 file 目录在同一级别。
  • $row['file'] 包含带扩展名的文件名。例如:image1.jpg 或
    doc1.xls
  • 你想在视图文件中显示图像,但你想 强制用户下载 .doc、.ppt、.pdf (application/octet-stream MIME 类型)

    您可以在同一级别创建另一个 php 文件来强制下载其他扩展。让我们将其命名为 download.php

在您的视图文件中

<?php 
$path = '/file/';
$filePath = $path . $row['file'];
$downloadExtensions = ['doc', 'ppt', 'txt']; // you can add more extensions
?>

<?php if (file_exists($filePath)): ?>
    <?php $extension = pathinfo($filePath, PATHINFO_EXTENSION); ?>


    <?php if (in_array($extension, $downloadExtensions)): ?>
        <a href="download.php?file=<?php echo $row['file']; ?>"><?php echo $row['file']; ?></a>
    <?php else: ?>
        <a href="<?php echo $filePath; ?>"></a>
    <?php endif; ?>
<?php endif; ?>

在download.php中

<?php
// download.php
$path = '/file/';
$fileName = $_GET['file'];
$filePath = $path . $fileName;

// verify that the file exists
if (file_exists($filePath) ) {
    // force the download
    header("Content-Disposition: attachment; filename=\"" .     basename($fileName) . "\"");
    header("Content-Length: " . filesize($filePath));
    header("Content-Type: application/octet-stream;");
    readfile($filePath);
}
?>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
相关资源
最近更新 更多