我试图创建一个下载文件功能,但它不起作用,它给我一个错误: “文件”/storage/app/candidates/cvs/3/1493594353.pdf“不存在”,但我只是看文件,就在那里。
我错过了什么吗?
注意:我正在使用laravel 5.4
文件结构:
storage
- app
-- candidates
---cvs
----3
-----1493594353.pdf
- public
路线:
Route::post('candidate/cv/download-cv/','CurriculumVitaeController@downloadCV');
控制器:
public function downloadCV()
{
$candidate = Candidate::where('user_id',Auth::user()->id)->first();
$candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();
$path = Storage::url('app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv);
$headers = ['Content-Type: application/pdf'];
$newName = 'cv-'.time().'.pdf';
return response()->download($path, $newName, $headers);
}
答案 0 :(得分:1)
将控制器下载方法更改为:
public function downloadCV()
{
$candidate = Candidate::where('user_id',Auth::user()->id)->first();
$candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();
$path = storage_path().'/app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv;
$headers = ['Content-Type: application/pdf'];
$newName = 'cv-'.time().'.pdf';
return response()->download($path, $newName, $headers);
}
此外,为了使事物更具动态性,您可以动态分配Content-type
和返回的文件扩展名,如下所示:
public function downloadCV()
{
$candidate = Candidate::where('user_id',Auth::user()->id)->first();
$candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();
$path = storage_path().'/app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv;
$headers = ['Content-Type: '.Storage::mimeType('/app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv)];
$newName = 'cv-'.time().'.'.pathinfo($path, PATHINFO_EXTENSION);
return response()->download($path, $newName, $headers);
}