使用PHP在POSTGRESQL数据库中上载/下载文件 [英] Upload/Download file in POSTGRESQL database with PHP

查看:93
本文介绍了使用PHP在POSTGRESQL数据库中上载/下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a php page where a user can upload a pdf file and store it in a Postgresql database. On another page the user may download or read the pdf file.

此刻,我发现了这一点:

At the moment I have found this:

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

我尝试过:

$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;

但这不起作用! :-(

But it doesn't work! :-(

推荐答案

您必须在php文件中使用标头。输出缓冲区必须为空。$ filecontent表示

You have to use headers in a php file. The output buffer has to be empty. $filecontent reprensent the pdf content from the database.

// 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文件

This code will make sure that your user will download the pdf file

这篇关于使用PHP在POSTGRESQL数据库中上载/下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆