本文介绍了Laravel文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的Laravel 5.3应用程序中有一个方法可以返回如下文件:
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);
}
我正在vue.js中这样获取请求:
I'm making a get request in vue.js like this:
show (file) {
Vue.http.get('/api/file/' + file);
}
结果是这样的:
这可能是什么问题?我希望浏览器可以下载图像.
What could be wrong here? I'm expecting that I the browser downloads the image.
-编辑-
当我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来访问它!
When I add it to my web.php it's working. But I need to acces it through my api!
推荐答案
添加标题:
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);
}
或使用自定义下载功能必须是这样的:
ORuse 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;
}
这篇关于Laravel文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!