Mcloud
Mcloud

Reputation: 29

Download File doesnt work

Im trying to create a download file functionality, but it doesnt work, it gives me a error of: "The file "/storage/app/candidates/cvs/3/1493594353.pdf" does not exist", but im just looking at the file, and is there.

Am i missing something?

Note: im using laravel 5.4

File structure:

storage
- app
-- candidates
---cvs
----3
-----1493594353.pdf
- public

Route:

Route::post('candidate/cv/download-cv/','CurriculumVitaeController@downloadCV');

Controller:

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

    }

Upvotes: 0

Views: 105

Answers (1)

crabbly
crabbly

Reputation: 5186

Change your controller download method to this:

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

Also, to make things more dynamic, you could assign the Content-type and the returned file name extension on the fly, like this:

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

Upvotes: 1

Related Questions