AdRock
112
2
Laravel

Download file from storage doesn't work when using parameter for filename

Posted 1 month ago by AdRock

I am trying to download a file from storage which downloads ONLY when I hardcode values for the file. This isn't what I want as I can make a reusable function where i can pass parameters for a filename.

This works as expected when I hardcode filename;

$date = (new DateTime())->format('d-m-Y H:i:s');

        $headers = array(
            'Content-Type:' => 'application/pdf',
            'Content-Disposition' => 'attachment;filename="' . $download. '_' . $date . '.pdf"',
            'Content-Length: ' =>  Storage::disk('public')->size('5ce95e577efec.pdf'),
            'Pragma' => ' no-cache',
            'Expires' => ' 0'
        );

        return Storage::disk('public')->download('5ce95e577efec.pdf', $download . '_' . $date . '.pdf', $headers);

but when I do this, it does nothing.

// get the filename from ajkax
        $filename = $request->input('filename');
        // get today's date
        $date = (new DateTime())->format('d-m-Y H:i:s');
        // create a new user friendly filebnamne for download
        $download =  $request->input('title') . '_' . $date . '.pdf';

        $headers = array(
            'Content-Type:' => 'application/pdf',
            'Content-Disposition' => 'attachment;filename="' . $download . '"',
            'Content-Length: ' =>  Storage::disk('public')->size($filename),
            'Pragma' => ' no-cache',
            'Expires' => ' 0'
        );

        // force download the file
        Storage::disk('public')->download($filename, $download, $headers);

I'm baffled why using a parameter got a filename would stop it working

Please sign in or create an account to participate in this conversation.