简体   繁体   中英

Laravel download varbinary file from SQL Server

I am to storing PDF files into varbinary(max) field, using Laravel 5 and SQl server 2016. The probelm is am trying to download the file from the SQL Server, but it continues to return corrupt files. When I upload, I use:

'file' => DB::raw("CONVERT(VARBINARY(MAX), '" . base64_encode(file_get_contents($upload_file)) . "')"),

When I download, I'm doing this:

$document = DB::table('files')
                ->selectRaw('CAST(file AS VARBINARY(MAX)) AS file')->first();

$pdf = base64_decode($document->file);

return response($pdf)
            ->header('Cache-Control', 'no-cache private')
            ->header('Content-Description', 'File Transfer')
            ->header('Content-type','application/pdf;base64')
            ->header('Content-length', strlen($pdf))
            ->header('Content-Disposition', 'attachment; filename=Teste')
            ->header('Content-Transfer-Encoding', 'binary');

The original files has 97kb, and when i download has 187kb. Any Help please!

Resolvede the problem: First i converted to Hexadecimal the file uploaded:

$datastring = file_get_contents($request->file('upload_file')); 
$unpack = unpack("H*hex", $datastring); 
$unpack = '0x'.$unpack['hex'];
//store DB
'file' => DB::raw("CONVERT(VARBINARY(MAX), $unpack)"),

Then when download, i had convert back to bin:

$file_contents = hex2bin($document->file);

return response($file_contents)
            ->header('Cache-Control', 'no-cache private')
            ->header('Content-Description', 'File Transfer')
            ->header('Content-type','application/pdf;base64')
            ->header('Content-length', strlen($file_contents))
            ->header('Content-Disposition', 'attachment; filename=aaaa')
            ->header('Content-Transfer-Encoding', 'binary');     

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM