Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cors Origin in Direct Path in laravel when calling images

now I build web application using laravel 5.2 as webserivce and angular2 as front page I use VR Library from http://cdn.pannellum.org My Issue When I call link Of Iamge from my database like mywebsite.com/public/Images/photo7.png return to me this message

'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5565' is therefore not allowed access.

but I Handled this issue before I start project to transfer data from laravel and angular but when I call my images from direct Path return to me this message

like image 517
PERSON Avatar asked Mar 26 '17 10:03

PERSON


1 Answers

Laravel 5 (L5): In my project in, when I return image (file) and want to avoid CORS i use following code (I change it a little by hand without testing but it should work):

private function responseFile($filePath, $fileMimeType,  $originalFileName) {

    $headers = array(
        'Content-Type' => $fileMimeType,
        //'Content-Disposition' => 'attachment; filename="'. $attachment->org_name . '"', - this header is added automaticaly
        "Access-Control-Allow-Origin" => request()->getSchemeAndHttpHost() // allow CORS (e.g. for images)
    );

    return response()->download($filePath, $originalFileName, $headers);
}

In this solution you don't need to touch apache .htaccess file (or nginx config files) at all (if you do it it will cause errors with headers duplication) - because in this case we use so called Simple CORS request.

You can also read this answer to avoid other problems which can cause that CORS error.

like image 188
Kamil Kiełczewski Avatar answered Oct 08 '22 03:10

Kamil Kiełczewski