【问题标题】:Laravel with postgresql, store and get binary dataLaravel 与 postgresql,存储和获取二进制数据
【发布时间】: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


【解决方案1】:

你的部分代码在 Laravel 7 中对我自己很有用。这里我的解决方案 100% 对我有用。我还在等它对你有帮助。对不起,我的英语不是我的母语。

        $dbh = DB::connection()->getPdo();
        $query = "SELECT *, trim(trailing from encode(uploaded_data,'base64')) AS encode_data FROM esq_inversion.view_documento_proyecto WHERE id = :id";
        $stmt = $dbh->prepare($query);
        $stmt->bindParam(':id', $id);
        $data = $stmt->execute();
        // Convert to binary and send to the browser
        $stream = base64_decode($data['encode_data']);

        return response()->streamDownload(function () use ($stream){
            $file = fopen('php://output', 'w');
            fwrite($file, $stream);
            fclose($file);
        }, $fileName,[
            'Content-Type' => $mime,
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-Disposition' => 'attachment;filename*=UTF-8\'\'' . $fileName.'";',
            'Expires' => '0',
            'Pragma' => 'public',
        ], 'attachment');

最好的问候,米格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2021-06-13
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多