How to download Postgres bytea column as file

前端 未结 6 1805
甜味超标
甜味超标 2020-12-24 06:13

Currently, i have a number of files stored in postgres 8.4 as bytea. The file types are .doc, .odt, .pdf, .txt and etc.

May i know how to download all the file store

6条回答
  •  一整个雨季
    2020-12-24 07:01

    If you have a lot of data to download then you can get the lines first and then iterate through each one writing the bytea field to file.

    $resource = pg_connect('host=localhost port=5432 dbname=website user=super password=************');
    
    // grab all the user IDs
    $userResponse = pg_query('select distinct(r.id) from resource r
                            join connection c on r.id = c.resource_id_from
                            join resource rfile on c.resource_id_to = rfile.id and         rfile.resource_type_id = 10
                            join file f on rfile.id = f.resource_id
                            join file_type ft on f.file_type_id = ft.id
                            where r.resource_type_id = 38');
    
    // need to work through one by one to handle data
    while($user = pg_fetch_array($userResponse)){
        $user_id = $user['id'];
        $query = 'select r.id, f.data, rfile.resource_type_id, ft.extension from resource r
                            join connection c on r.id = c.resource_id_from
                            join resource rfile on c.resource_id_to = rfile.id and rfile.resource_type_id = 10
                            join file f on rfile.id = f.resource_id
                            join file_type ft on f.file_type_id = ft.id
                            where r.resource_type_id = 38 and r.id = ' . $user_id;
    
        $fileResponse = pg_query($query);
        $fileData = pg_fetch_array($fileResponse);
        $data = pg_unescape_bytea($fileData['data']);
        $extension = $fileData['extension'];
        $fileId = $fileData['id'];
        $filename = $fileId . '.' . $extension;
        $fileHandle = fopen($filename, 'w');
        fwrite($fileHandle, $data);
        fclose($fileHandle);
    }
    

提交回复
热议问题