如何使用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);
答案 0 :(得分:1)
您的代码的一部分对Laravel 7来说对我自己很有用。在这里,我的解决方案对我而言100%可用。我仍在等待,它将为您提供帮助。对不起,我的英语不是我的母语。
<!DOCTYPE html>
<html>
<head>
<script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script>
</head>
<body>
</body>
</html>
最诚挚的问候,米格