The issue you're facing is likely related to the Content-Type header in your response. The pathinfo function is used to determine the file extension, but it might not always return the correct MIME type for the image. Additionally, if the file extension is not recognized, the browser might not display the image correctly.
Here's a solution to ensure the correct MIME type is used:
- Use the
mime_content_typefunction to determine the correct MIME type of the file. - Ensure that the SFTP disk is correctly configured in your
config/filesystems.phpand.envfile.
Here's how you can modify your ImageController:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
class ImageController extends Controller
{
public function show($filename)
{
$disk = Storage::disk('sftp');
if ($disk->exists($filename)) {
\Log::info('exists');
$fileContent = $disk->get($filename);
$tempFilePath = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFilePath, $fileContent);
$mimeType = mime_content_type($tempFilePath);
unlink($tempFilePath);
return response()->stream(function () use ($fileContent) {
echo $fileContent;
}, 200, [
'Content-Type' => $mimeType,
'Content-Disposition' => 'inline; filename="' . $filename . '"',
]);
}
abort(404);
}
}
Explanation:
-
Temporary File: We create a temporary file to determine the MIME type using
mime_content_type. This function reads the file's content to determine its type, which is more reliable than using the file extension. -
MIME Type: The correct MIME type is set in the
Content-Typeheader, ensuring the browser can render the image properly. - Cleanup: The temporary file is deleted after determining the MIME type to avoid cluttering the server with temporary files.
Make sure your SFTP configuration in config/filesystems.php and .env is correct and that the server has the necessary permissions to access the files. This should resolve the issue and allow the images to be displayed correctly.