下载带有audio / mpeg mime类型的文件

时间:2011-09-03 13:09:57

标签: php http-headers mime readfile

我正在尝试使用audio / mpeg mime类型下载 远程 mp3文件,而不是右键单击链接然后另存为。我尝试用php头修改头内容类型,然后用readfile()调用该文件。这非常有效但是由于readfile()命令,文件来自我的服务器带宽。是否有另一种方法来更改标头而没有带宽成本?我可以定义浏览器如何使用javascript处理内容类型?有没有人有同样的问题?

提前致谢。

2 个答案:

答案 0 :(得分:1)

通过使用mime type audio / mpeg,您告诉浏览器“使用此文件执行默认操作”。例如,如果你有一个jpg文件并将mime类型设置为image / jpeg,浏览器将读取jpg并在浏览器窗口中显示它。

解决方案是使用mime类型的应用程序/数据。这将下载文件,将浏览器从中删除。

那将是

header("Content-type: application/data");

==已更新==

更完整的方法

header("Content-type: application/data");
header("Content-Disposition: attachment; filename=$this->filename");
header("Content-Description: PHP Generated Data");
readfile($this->file);

如果你想要一个动态的mime类型的阅读器,你可以使用这个

$type = $this->get_mime_type($this->filename);
header("Content-type: " . $type);

...

private function get_mime_type($filename) {

    $fileext = substr(strrchr($filename, '.'), 1);

    if (empty($fileext)) {
        return (false);
    }

    $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext)/i";
    $lines = file("mime.types", FILE_IGNORE_NEW_LINES);

    foreach ($lines as $line) {
        if (substr($line, 0, 1) == '#') {
            continue; // skip comments
        }

        if (!preg_match($regex, $line, $matches)) {
            continue; // no match to the extension
        }

        return ($matches[1]);
    }
    return ("application/data");  // no match at all, revert to something that will work
}

并且,要获取mime类型列表,您可以检查我的实验室版本,保存显示的内容并将其保存到您网站根目录中名为mime.types的文件中。

http://www.trikks.com/lab/mime.html

玩得开心

答案 1 :(得分:0)

我认为你需要做的是:

$pathOfAudioFile = '/path/to/my/file.mp3';

header('Content-Type: audio/mpeg');
header('Content-Length: '.filesize($pathOfAudioFile));

// This next line forces a download so you don't have to right click...
header('Content-Disposition: attachment; filename="'.basename($pathOfAudioFile).'"');

readfile($pathOfAudioFile);

使用Content-Disposition: attachment...强制显示下载框,而不必右键单击 - >将目标另存为。