Download Laravel File

I have 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 am making a get request in vue.js like this:

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

      

The result will be the following:

enter image description here

What could be wrong here? I expect the browser to load the image.

- EDIT -

enter image description here

When I do dd($path);

, this is the result:/home/vagrant/Code/forum/storage/app/users/3/messages/xReamZk7vheAyNGkJ8qKgVVsrUbagCdeze.png

The route is in mine api.php

:

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

      

When I add it to my web.php it works. But I need to get it through my api!

0


source to share


2 answers


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!

0


source


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 the custom load function should 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;
}

      

0


source







All Articles