To display a PDF stored on a remote server using SFTP, you need to ensure that the URL used in the <embed> tag is correctly pointing to a route that serves the file. Here are some steps and corrections you can make to ensure the PDF is displayed correctly:
-
Correct the URL in the View: Ensure that the URL in the
<embed>tag points to the correct route that serves the file. You should use theroute()helper to generate the URL for theserveFileroute.Update your view to use the correct URL:
@foreach($files as $file) {{ $file->name }} <br> <embed src="{{ route('file.serve', ['filename' => $file->name]) }}" width="600" height="400"> @endforeach -
Define Named Route: Make sure your route for serving the file is named so you can reference it easily in your view.
Update your routes file:
Route::get('/file/{filename}', [FileController::class, 'serveFile'])->name('file.serve'); -
Ensure Correct MIME Type Detection: The
File::mimeType()method you are using might not be correct. Instead, use thefinfo_file()function to determine the MIME type.Update the
serveFilemethod in your controller:public function serveFile($filename) { $disk = Storage::disk('sftp'); if (!$disk->exists($filename)) { abort(404, 'File not found'); } $fileData = $disk->get($filename); // Determine the MIME type $tempFilePath = sys_get_temp_dir() . '/' . $filename; file_put_contents($tempFilePath, $fileData); $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $tempFilePath); finfo_close($finfo); unlink($tempFilePath); return response($fileData, 200) ->header('Content-Type', $mimeType); } -
Check File Path: Ensure that the file path stored in your database is correct and matches the path used in the SFTP storage. The path should be relative to the root of the SFTP storage.
By following these steps, you should be able to correctly display the PDF files stored on your remote server. Make sure to test the file paths and MIME type detection to ensure everything is working as expected.