【问题标题】:Upload/Download file in POSTGRESQL database with PHP使用 PHP 在 POSTGRESQL 数据库中上传/下载文件
【发布时间】:2014-10-06 17:35:19
【问题描述】:

我想创建一个 php 页面,用户可以在其中上传 pdf 文件并将其存储在 Postgresql 数据库中。在另一个页面上,用户可以下载或阅读 pdf 文件。

目前我发现了这个:

POSTGRESQL:

CREATE TABLE schema.tab
(
  id serial NOT NULL,
  a bytea,
  CONSTRAINT tab_pkey PRIMARY KEY (id)
)

PHP 上传:

if ($_POST[submit]=="submit"){

    include_once('../function.php');
    ini_set('display_errors','Off');
    $db=connection_pgsql() or die('Connessione al DBMS non riuscita');

    $data = file_get_contents($_FILES['form_data']['tmp_name']);
    $escaped = pg_escape_bytea($data);
    $result = pg_prepare( "ins_pic",'INSERT INTO schema.tab (a) VALUES ($1)'); 
    $result = pg_execute ("ins_pic",array('$escaped')); 

现在我如何使用id=1下载存储在标签中的pdf?

我试过了:

$sql= "SELECT a FROM schema.tab WHERE id=5";


$resource=pg_query($db, $sql);
$row=pg_fetch_array($resource, NULL, PGSQL_BOTH);


$data = pg_unescape_bytea($row[0]);

$extension ='pdf';
$fileId = 'title';

$filename = $fileId . '.' . $extension;

$fileHandle = fopen($filename, 'w');
fwrite($fileHandle, $data);
fclose($fileHandle);


// We'll be outputting a PDF
header('Content-type: application/pdf');


// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
echo $fileHandle;
exit;

但它不起作用! :-(

【问题讨论】:

  • 旁注:[submit] 周围缺少引号
  • 以 Stack 上的问答为基础 => stackoverflow.com/q/14418725
  • 您是在尝试将文件存储在数据库中(即在 BLOB 中),还是对文件的引用(如在文件路径或 URL 中)?对答案有很大影响。
  • 不,我想将它存储在数据库中。

标签: php postgresql


【解决方案1】:

您必须在 php 文件中使用标头。输出缓冲区必须为空。 $filecontent 代表数据库中的 pdf 内容。

// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
echo $filecontent;
exit;

此代码将确保您的用户将下载 pdf 文件

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2014-12-26
    • 2013-04-07
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多