AnkurPrem's avatar

Renaming uploaded file before download

So, I want the user to download a file with another name than the stored one.

For example:

File is stored as: storage/app/uploaded/7HjQ1Cnhf8zeRrUUMLI9NZtIKyvRDYqNWCIvh8Qm.txt

And I want the user to download this file as file.txt

$path = storage_path('app/'.$file);
???
return response()->download($path);

Someone can help me with that?

0 likes
5 replies
tykus's avatar
tykus
Best Answer
Level 104

Not something I use very frequently, but the method signature accepts a $name, which I would expect sets the downloaded file name?

return response()->download($pathToFile, $name, $headers);
2 likes
AnkurPrem's avatar

Yeah, tykus, works fine! Thank you.

1 like
maltekiefer's avatar

Hello, I tried it like this:

    public function file($filename){

        $path = File::where('name', $filename)->first();

        $filename_new = str_replace('/storage/assets/', '', $path->file_path);
        $ext = pathinfo($path->file_path, PATHINFO_EXTENSION);
        $headers = array(
            'Content-Type: '.Storage::mimeType('assets/'.$filename_new),
        );

        if (!Storage::disk('local')->exists('assets/'.$filename_new)){
            return response()->json('', 404);
        }

        return Storage::download('assets/'.$filename_new, $path->customname.'.'.$ext, $headers);
    }
}

But the downloaded file has still the original filename

automica's avatar

@maltekiefer please start a new thread for your question rather than reopening an old, answered one.

Please or to participate in this conversation.