0

I've got a method in my Laravel 5.3 application that returns a file like this:

public function show(File $file)
{
    $path = storage_path('app/' . $file->getPath());
    return response()->download($path, $file->name);
}

I'm making a get request in vue.js like this:

show (file) {
    Vue.http.get('/api/file/' + file);
}

The result is this:

enter image description here

What could be wrong here? I'm expecting that I the browser downloads the image.

--EDIT--

enter image description here

When I dd($path); this is the result: /home/vagrant/Code/forum/storage/app/users/3/messages/xReamZk7vheAyNGkJ8qKgVVsrUbagCdeze.png

The route is in my api.php:

Route::get('/file/{file}',                             'File\FileController@show');

When I add it to my web.php it's working. But I need to acces it through my api!

Jamie
  • 10,302
  • 32
  • 103
  • 186

2 Answers2

0

You can do it like this:

public function show(File $file)
{
    $path = storage_path('app/' . $file->getPath());
    $headers = array(
      'Content-Type: image/png',
    );
    return response()->download($path, $file->name, $headers);
}

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
0

Add headers :

public function show(File $file)
{
  $path = storage_path('app/' . $file->getPath());
  if(!file_exists($path)) throw new Exception("Can't get file");
  $headers = array(
    "Content-Disposition: attachment; filename=\"" . basename($path) . "\"",
    "Content-Type: application/force-download",
    "Content-Length: " . filesize($path),
    "Connection: close"
  );
  return response()->download($path, $file->name, $headers);
}

OR use custom download function must be like this :

function download($filepath, $filename = '') {
    header("Content-Disposition: attachment; filename=\"" . basename($filepath) . "\"");
    header("Content-Type: application/force-download");
    header("Content-Length: " . filesize($filepath));
    header("Connection: close");
    readfile($filepath);
    exit;
}
Fky
  • 2,133
  • 1
  • 15
  • 23
  • Hi, Thanks for helping me. I've done that ^. When I look at the image in my network tab (see edit that I've made above) it's showing the headers. But it's not working :( – Jamie Nov 10 '16 at 16:04
  • did you try to make my second option ? First i think you have to test file existence , are you sur the path is correct and image is accessible ? – Fky Nov 10 '16 at 16:16
  • When I add the route to ```web.php``` instead of ```api.php``` it's working but I need to acces it from my api. – Jamie Nov 10 '16 at 16:57
  • you need to make a service from web and call it from api – Fky Nov 10 '16 at 16:59
  • When I do that it's not working in my vue.js application. But when I acces it through the browser it's working. – Jamie Nov 10 '16 at 17:05
  • And I've to make an api request because I'm using JWT Auth. – Jamie Nov 10 '16 at 17:08