Reputation: 1300
I am working on a laravel project in which I am trying to show image using url
but getting error
. I have tried a lot and search everything but I don't understand why I am getting this error. I am using the below function
public function displayImage($filename){
$path = storage_path("app/taskImage/".$filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = \Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
And the route is
Route::get('taskImg/{filename?}', [
'uses' => 'FormController@displayImage',
]);
And the URL which I am tring is like
http://localhost/project_name/public/taskImg/test.jpg
when I have print something I am getting the that but Not getting the Image. It is showing a blank screen with error message The image cannot be displayed because it contains errors
Upvotes: 2
Views: 1142
Reputation: 1
TLDR: there might be a newline before a <?php in a PHP file, just search for it, remove it, and check if error persists.
In case 5 years later, someone comes across this same error... I have just experienced it and after applying the line suggested by shamaseen
just add ob_end_clean
ob_end_clean();
and verifying it fixed the issue, I went on a search to find why it did fix. Apparently that function clears the stream buffer. After asking GPT for help, it suggested checking if there was something in the buffer, which I did by placing this line at the start of my controller.
dd(ob_get_contents());
which returned the following in the browser:
"\n" // app/Http/Controllers/FileUpload/GetFileController.php:14
and that is a newline code, which was forgotten in a PHP file right before the <?php starting tag, in my case the localization file
\n #it wasn't visible because it's just a blank line
<?php
return [
'locales' => ['en', 'pt'],
];
So I just removed it and, it works correctly again.
Upvotes: 0
Reputation: 2488
I've spent a LOT of hours searching for a solution for this, I found it at last! just add ob_end_clean
before returning the response, like the following:
ob_end_clean();
return response()->file($path,['Content-type' => 'image/jpeg']);
I can't explain because I don't know what was going on, any one could explain this?
Upvotes: 4
Reputation: 1128
you can do it like this way
$storagePath = storage_path("app/taskImage/".$filename);
return Image::make($storagePath)->response();
Upvotes: 0