Laravel file download

2019-09-15 01:26发布

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!

2条回答
Root(大扎)
2楼-- · 2019-09-15 02:03

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!

查看更多
放我归山
3楼-- · 2019-09-15 02:09

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;
}
查看更多
登录 后发表回答