我的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访问它!
答案 0 :(得分:0)
你可以这样做:
public function show(File $file)
{
$path = storage_path('app/' . $file->getPath());
$headers = array(
'Content-Type: image/png',
);
return response()->download($path, $file->name, $headers);
}
希望这有帮助!
答案 1 :(得分:0)
添加标题:
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 使用自定义下载功能必须是这样的:
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;
}