laravellaravel-5.7

The image cannot be displayed because it contains errors laravel


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


Solution

  • 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?