How to serve files for download? Trying to serve files for users to view/download, but server responds with wrong Content-Type
I have a functionality on a website in which the user logs in and then a list of files available for download is showed. When he clicks on the file, it should show a download dialog with the options for open with the application if one is installed for the filetype (like Acrobat Reader if it is installed, for example) or prompt download if it's not. Currently, I'm building the list using PHP just echoing each file's path. Then, when the user clicks on the link, the browser directly requests the file. My first problem with this was that ppsx or pptx files were displayed in the browser as plain text files, resulting on garbage-on-screen. Then I added an .htaccess file on the directory where the files to be served are, with this content:
Options All -Indexes
Header set Content-Disposition attachment
With that .htaccess file, the browser dialog appears but, for example, in Firefox, it has the option "Open with: Notepad", instead of the correct application for th开发者_运维百科e file or none if there isn't an application installed for the filetype. I can see that the response header Content-Type is "text/plain" and that's wrong, but how can I make the correct Content-Type be detected by the server?
Thanks a lot.
You need to use the correct MIME Content-Type to get the appropriate response from the browser for a specific file type.
Powerpoint is:
application/vnd.ms-powerpoint
You can modify your .htaccess file for the updated MIME types as shown on this site.
Ok, I gave up and rewrited how it works. In my views, I print the path to a controller method and pass a parameter to it with the file id. The controller checks the user id with the session, looks for the file in the database and then there is this code:
if (file_exists($file['path'])) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$file['name']);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file['path']));
ob_clean();
flush();
readfile($file['path']);
exit;
}
It successfuly makes the browser to popup a download dialog also giving the option to open it with the associated application if it's installed.
精彩评论