【发布时间】:2018-09-16 22:17:54
【问题描述】:
如何使用 Laravel 从 postgres bytea 字段中存储和获取数据? 我想更新二进制数据并下载它们。 文件类型有jpg、excel、txt等。 可以吗?
目前我要存储的代码。
public function store_db( $file, $file_name, $user_id ) {
$file_path = $file->getRealPath();
$new_attachment = Attachment::create([
'name' => $file_name,
'mime' => $file->getClientMimeType(),
'size' => $file->getClientSize(),
'uploaded_data' => pg_escape_bytea(file_get_contents($file_path)),
'created_by' => $user_id,
'updated_by'=> $user_id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
return $new_attachment->id;
接下来获取和下载数据(jpg、excel等)
public function get_attachment( $id ) {
$file = $this->attachmentRepository->findWithoutFail($id);
$dbh = DB::connection()->getPdo();
$stmt = $dbh->prepare("SELECT name, mime, trim(trailing from encode(uploaded_data,'escape')) AS encode_data FROM attachments WHERE attachments.id = :atid");
$stmt->bindParam(':atid', $id);
$stmt->execute();
$result = $stmt->fetch($dbh::FETCH_ASSOC);
$name = $result['name'];
$mime = $result['mime'];
$headers = array(
"Content-Type: {$mime}",
);
$fileData = $result['encode_data'];
$ext = substr($name, strrpos($name, '.') + 1);
file_put_contents($ext , pg_unescape_bytea($fileData));
return response()->download($ext, $name, $headers);
【问题讨论】:
-
你做的手工工作太多了。 eloquent 不会为您处理准备好的语句吗?
-
你是对的。但是我如何通过 laravel eloquent 从 postgresql 获取 bytea 数据?
-
似乎 laravel 不支持开箱即用,但您可能可以使用像例如laravel.com/docs/5.6/eloquent-mutators
标签: php laravel postgresql download binary