开发者

downloading files with audio/mpeg mime type

I am trying to download remote mp3 files with an audio/mpeg mime type instead of right clicking on the link 开发者_运维问答then saving as. I have tried modifying the header content-type with php headers and then calling the file with readfile(). This worked very well but because of the readfile() command the files came out of my servers bandwidth. is there another way of changing the header without the cost of bandwidth? can i define how the browser handles with content type with javascript? has anyone had the same problem?

Thanks in advance.


By using the mime type audio/mpeg you tell the browser to "do your default action with this file". In example if you have an jpg file and set the mime type to image/jpeg the browser will read the jpg and display it inside the browser window.

The solution is to use the mime type application/data instead. This will download the file leaving the browser out of it.

That would be

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

== Updated ==

A more complete approach

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

If you want a dynamic mime type reader you could use this

$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
}

And, to get a list of mime types you can check my lab version, save the displayed content and save it to a file named mime.types in the root of your website.

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

Have fun


I think what you need to do is this:

$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);

Using Content-Disposition: attachment... forces a download box to appear instead of having to right click -> save target as.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜