使用PHP在POSTGRESQL数据库中上传/下载文件


Upload/Download file in POSTGRESQL database with PHP

我想创建一个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;

但它不起作用!:-(

您必须在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文件