gpt4 book ai didi

php - 使用 Laravel 上传和显示保存在 PostgreSQL 中的 PDF 文件

转载 作者:行者123 更新时间:2023-11-29 12:24:02 24 4
gpt4 key购买 nike

我有一个项目要求我在数据库中保存一个 PDF 文件(字面上将文件保存在数据库中,而不是路径)。我正在使用 PostgreSQL 10 和 Laravel 5.6。这是我的迁移文件:

public function up()
{
Schema::create('uploads', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('mime');
$table->binary('data'); // generate a bytea column after running migration
$table->timestamps();
});
}

下面是我的 Controller 中上传 PDF 文件的功能:

public function upload(Request $req)
{
$name = pg_escape_string($_FILES['fpdf']['name']);
$type = pg_escape_string($_FILES['fpdf']['type']);
$data = pg_escape_bytea(file_get_contents($_FILES['fpdf']['tmp_name']));

DB::table('uploads')
->insert(['name' => $name, 'mime' => $type, 'data' => $data]);

return "success upload";
}

PDF文件上传成功: Result showed in pgAdmin

但问题是,PDF 文件无法在浏览器中显示(下载)。 这是我的 Controller 中用于在浏览器中显示 PDF 文件的功能:

public function showPDF($id)
{
$pdf = Upload::find($id);
return view('upload/pdf', compact('pdf'));
}

查看文件:

<?php
$content = pg_unescape_bytea(stream_get_contents($pdf->data));
echo "<embed src='data:". $pdf->mime .";base64,".base64_encode($content)."' />";
?>

输出是: Output for displaying the PDF file in the browser


我试图通过使用关键字“上传和显示存储在 PostgreSQL 数据库中的 PDF 文件”浏览 stackoverflow 和其他问答网站上的许多问题来找到解决方案,但不幸的是我找不到任何关于如何做的答案显示 PDF 文件。

我在 YouTube ( Insert File into MySQL Blob with PHP ) 上找到了一个视频,但在尝试之后,仍然没有成功。

我的问题是,如何使用 Laravel 5.6 框架在浏览器上显示/下载 PostgreSQL 数据库中保存的 PDF 文件?

============================================= ===================

我根据 Devon 的建议修改了我的 showPDF 函数,但我得到了以下输出:

latest output

这是修改后的 showPDF 函数:

public function showPDF($id)
{
$pdf = Upload::find($id);
$content = pg_unescape_bytea(stream_get_contents($pdf->data));
return response($content)->header('Content-Type', $pdf->mime);
}

最佳答案

现在大多数浏览器都内置了 PDF 阅读器,通常没有理由使用嵌入,除非您想实际将 PDF 嵌入到其他内容中。

为此,您应该能够从 Controller 返回带有为 Content-Type 设置的 header 的响应:

return response($content)->header('Content-Type', $pdf->mime);

关于php - 使用 Laravel 上传和显示保存在 PostgreSQL 中的 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51457746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com