【问题标题】:Laravel file downloadLaravel 文件下载
【发布时间】:2017-03-24 17:20:37
【问题描述】:

我的 Laravel 5.3 应用程序中有一个方法可以返回如下文件:

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

我正在像这样在 vue.js 中发出 get 请求:

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

结果是这样的:

这里可能有什么问题?我期待我的浏览器下载图像。

--编辑--

当我dd($path); 这是结果:/home/vagrant/Code/forum/storage/app/users/3/messages/xReamZk7vheAyNGkJ8qKgVVsrUbagCdeze.png

路线在我的api.php:

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

当我将它添加到我的 web.php 时,它正在工作。但我需要通过我的 api 访问它!

【问题讨论】:

  • download() 方法中添加标题作为第三个参数
  • 什么样的标题?我以为他们已经包括在内了。
  • 你能在你的问题中显示dd($path)吗?
  • @Amit 确定:"/home/vagrant/Code/forum/storage/app/users/3/messages/xReamZk7vheAyNGkJ8qKgVVsrUbagCdeze.png"
  • 我怀疑你为什么在 public function show(File $file) 中输入 -hinting File。我认为通过查看您的route 文件,它应该是一个字符串,如public function show($file)

标签: php file laravel vue.js


【解决方案1】:

你可以这样做:

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

希望这会有所帮助!

【讨论】:

  • 谢谢,但我仍然收到相同的!
【解决方案2】:

添加标题:

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);
}

或 使用自定义下载功能必须是这样的:

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;
}

【讨论】:

  • 您好,感谢您的帮助。我已经做到了^。当我查看我的网络选项卡中的图像时(请参阅我在上面所做的编辑),它显示了标题。但它不起作用:(
  • 您是否尝试过我的第二个选项?首先我认为你必须测试文件是否存在,你的路径是否正确并且图像是否可以访问?
  • 当我将路由添加到 web.php 而不是 api.php 时,它正在工作,但我需要从我的 api 访问它。
  • 你需要从web做一个服务并从api调用它
  • 当我这样做时,它在我的 vue.js 应用程序中不起作用。但是当我通过浏览器访问它时它正在工作。
猜你喜欢
  • 2018-02-02
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多