John Davidson

php - view pdf stored on public/storage on laravel?

0 comments
Message:


My code doesn't save pdf's, I need to show it. If it's possible download it too.


<td><a name="Manual" href="{{asset('storage/app').'/'.$machineData->getManual()}}">
Manual de {{$machineData->getMachineName()}}</a></td>

On controller I have this


protected function downloadFile($src)
{
if(is_file($src))
{
$finfo=finfo_open(FILEINFO_MIME_TYPE);
$content_type=finfo_file($finfo,$src);
finfo_open($finfo);
$file_name=basename($src).PHP_EOL;
$size=filesize($src);
header("Content-Type: $content_type");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Transfer-Encoding: binary");
header("Content-Length: $size");

return true;
}
else
{
return false;
}
}
public function download(Request $request)
{
$note=$request->file('manual');
if(!$this->downloadFile(app_path(). $note))
{
return redirect("/machineIndex");

}

}

Please help, I just want to show the file, thanks!!



My Answer:
To view and download a PDF file stored in the public/storage directory in Laravel, you can use the following code:

In your blade file:
html

Manual de {{ $machineData->getMachineName() }}



In your controller:
php
public function download(Request $request)
{
$note = $request->file('manual');
$filePath = storage_path('app/' . $note);

if (file_exists($filePath)) {
return response()->file($filePath);
} else {
return redirect("/machineIndex");
}
}


This code will generate a link in your view that will open the PDF file in a new tab when clicked. If you want to force the download of the file instead, you can modify the controller code to use the `response()->download()` method instead of `response()->file()`.

Rate this post

5 of 5 based on 2486 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us