xHtml下载文件到硬盘

时间:2011-08-20 13:04:18

标签: html css xhtml

是否可以将文件从我的服务器直接下载到用户的硬盘?当我尝试下载CSS文件时,我的浏览器只是在新浏览器中打开css文件(几乎就像Microsoft Word一样)。我希望用户拥有实际的 css文件。

代码

<a href="Stylesheets/custom.css" rel="external">Download This File</a>

2 个答案:

答案 0 :(得分:1)

如果要强制下载提示,最简单的方法是使用某种服务器端脚本语言来修改标题,使其包含Content-Disposition: attachment; filename="file.ext"。这在PHP中非常简单,但它实际上取决于您的服务器可用的语言/设施。

您可以对服务器配置本身进行强制执行此操作 - 如何执行此操作取决于您运行的服务器。

如果你想在PHP中这样做,这里有一个简短的例子:

getcss.php(与HTML文件放在同一目录中,其中包含链接)

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

?>

然后您的链接将是:

<a href="getcss.php?file=Stylesheets/custom.css">Download This File</a>

答案 1 :(得分:1)

如果您使用Apache和/或PHP,并且能够修改您的服务器配置,或者(可能,取决于限制)使用htaccess文件,则需要设置要从服务器发送的Content-Disposition标头(或者在单独的PHP文件中,如果使用PHP)。不确定如果使用ASP或没有编程语言需要什么..

此示例来自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');

在你的情况下会是:

// 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

这意味着您要么必须在其中创建包含上述代码的PHP页面,而是链接到该页面,或者将类似内容添加到htaccess:

<FilesMatch "(?i)^.*custom.css$">
   Header set Content-Disposition attachment
</FilesMatch>

更新:抓住htaccess的事情。这可能会让你下载试图在你的页面上呈现的样式表,除非你使用了不同的文件匹配类型条件,并且有你希望用户在单个文件夹中下载的文件。