0

I managed to send an image using File Response: https://laravel.com/docs/9.x/responses#file-responses

From the Controller:

public function get_image(Request $request) {
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';
    return response()->file($pathToFile); }

But I need to return multiple images, but this doesn't work (In this example I use the same image just for the test):

public function get_images(Request $request)
{
    $images = [];
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';

    for ($i = 0; $i < 20; $i++) {
        $images[] = response()->file($pathToFile);
    }
    return $images;
}

It only returns array of empty headers. I am using Fetch API (Or AJAX) to get the images

pileup
  • 1
  • 2
  • 18
  • 45
  • 1
    Well you can't do that, you will need to download each file with a different request, you can't have multiple responses for a single request, it's not related to laravel, but it's how http works, see : https://stackoverflow.com/questions/2339440/download-multiple-files-with-a-single-action . You can however make a zip file – Lk77 Dec 08 '22 at 08:38
  • I just wonder what is the best practice for my case, where I need to load 20 images every time (infinite scroll) - will I need to zip it, send it to frontend then unzip in frontend? Is it a good practice or it's too much of a performance hit? – pileup Dec 08 '22 at 08:53
  • 2
    the best practice is to use apache/nginx to load the images, and not laravel – Lk77 Dec 08 '22 at 08:56
  • I am using nginx, what should I do? Also, what do you mean by apache? Do you have a link to explanation where I can learn about it? Never done that before (Can I use both nginx as the server and apache to load the images?) – pileup Dec 08 '22 at 08:57
  • Well it depends on the webserver you use, if you use nginx then use it to handle file downloads, there is not much to do, put the files in a public folder somewhere that is served by nginx – Lk77 Dec 08 '22 at 08:59
  • Ok so the problem is (and why I used Laravel) is that these are user uploaded private images, so I did not want to put them in the publicly accessible folder - I put that below root. Maybe that's not how I should be doing it then? – pileup Dec 08 '22 at 09:13
  • You could try something like : https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/ i've not used it myself, but it seems to allow access to private files with nginx, by passing a header – Lk77 Dec 08 '22 at 09:36

0 Answers0