xHtml download file to hard drive
Is it possible to download a file from my server directly to 开发者_C百科a user's hard drive? when I try to download a CSS file, my browser just opens the css file in a new browser (almost like Microsoft Word would). I want the user to have the actual css file though.
Code
<a href="Stylesheets/custom.css" rel="external">Download This File</a>
If you want to force a download prompt, the simplest way to do it is to use some kind of server-side scripting language to modify the headers so they include Content-Disposition: attachment; filename="file.ext"
. This is very easy in PHP, but it really depends on what languages/facilities your server has available.
There are things you can do to the server configuration itself to force this as well - how you do it depends on the server you are running.
If you wanted to do it in PHP, here is a short example:
getcss.php (placed in the same directory as the HTML file with the link in it)
<?php
if (!isset($_GET['file']) || !file_exists($_GET['file'])) {
header('HTTP/1.1 404 File Not Found');
exit;
}
header('Content-Type: text/css');
header('Content-Length: '.filesize($_GET['file']));
header('Content-Disposition: attachment; filename="'.basename($_GET['file']).'"');
readfile($_GET['file']);
exit;
?>
Then your link would be:
<a href="getcss.php?file=Stylesheets/custom.css">Download This File</a>
If you use Apache and/or PHP, and are able to modify your server configuration, or (possibly, depending on restrictions) use a htaccess file, you need to set the Content-Disposition header to be sent from the server (or in a separate PHP file, if using PHP). Unsure what would be required if you use ASP, or no programming language..
This example from PHP.net:
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
In your case would be:
// We'll be outputting a CSS
header('Content-type: text/css'); // if this doesnt work, try application/octet-stream instead of text/css
// It will be called custom.css
header('Content-Disposition: attachment; filename="custom.css"');
// The CSS source is in custom.css
readfile('custom.css'); // http://php.net/manual/en/function.readfile.php
This means you'd either have to make a PHP page with the above code in it, and link to that instead, or add something like this to htaccess:
<FilesMatch "(?i)^.*custom.css$">
Header set Content-Disposition attachment
</FilesMatch>
Update: scratch the htaccess thing. That'd probably make you download stylesheets that are trying to render on your page, unless you used a different filesmatch type condition, and had files you wanted users to download in an individual folder.
精彩评论