У меня есть база PostgreSQL с таблицей для хранения файлов. Сам файл храниться в поле bytea. Как мне правильно организовать загрузку и скачивание файла? У меня получается загружать файл в базу, но я не могу его оттуда корректно скачать, т.е. файл скачивается, но видимо в битой кодировке/формате, потому что он не открывается в программе (excel файл). Вот мои обработчики (использую фреймворк Laravel):
Загрузка:
public function submit(Request $req){
if($req->hasFile('upload_file')){
$date = date('Y-m-d H:i:s', time()+60*60*2);
$file=file_get_contents($req->file('upload_file'));
$size=$req->file('upload_file')->getSize()/1024;
$file = base64_encode($file);
$name=$req->file('upload_file')->getClientOriginalName();
$user = DB::table('Users')->where('Login', session('user'))->first();
DB::table('FileJournal')->insert(['name'=>$name,'ID_User'=>$user->ID,'file'=>$file,'Directory'=>"null",'DateInsert'=>$date,'Size'=>$size,'IsLoaded'=>'true']);
return back()->with('Success',"Файл успешно загружен");
}
else {
return back()->withErrors('Нет файла');
}
}
Скачиваение:
public function download($file_id){
$dbconn = pg_connect("dbname=resource39 host=62.109.23.82 port=5432 user=resource_admin password=gcdxwYbv717");
$res = pg_query("SELECT * FROM \"System\".\"FileJournal\" WHERE \"ID\" =".$file_id);
$row = pg_fetch_assoc($res);
$size = $row['Size']*1024;
$file = pg_escape_bytea($row['file']);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$row['name']);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $row['Size']);
echo $file;
exit();
}
HTML-Страница
@if($errors->any())
<div class="alert alert-danger">
@foreach($errors->all() as $error)
{{$error}}
<br>
@endforeach
</div>
@endif
@if(session()->get('Success'))
<div class="alert alert-success">
{{session()->get('Success')}}
</div>
@endif
<form action="{{route('upload')}}" enctype="multipart/form-data" method="post">
<div class="upload_input">
@csrf
<input type="file" accept="application/vnd.ms-excel,application/xml,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" name="upload_file" id="upload_file">
<input type="submit" value="Отправить">
</div>
</form>
<div class="subpage_table">
<table border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<td>Наименование файла</td>
<td>Дата загрузки</td>
<td>Размер файла</td>
<td>Пользователь</td>
<td>Скачать</td>
</tr>
<thead>
<tbody>
@foreach ($journal as $record)
<tr>
<td>{{$record->name}}</td>
<td>{{date('d.m.Y H:i:s',strtotime($record->DateInsert))}}</td>
<td>{{round(($record->Size),2)}} Кб</td>
<td>{{$record->user}}</td>
<td><a href="{{route('download',['file_id' => $record->ID])}}" download><button><div class="download"></div></button></a></td>
</tr>
@endforeach
</tbody>
</table>
</div>