php MP3文件下载功能的实现

方式一:生成文件,返回一个链接,window.href = 链接;

方式二:hearder输出文件流。

先设置流的Content-Type和web服务器的mime类型。

mime类型参考

一个header文件流下载mp3文件的实例,

服务器端:
function
download(){ $full_path = 'pro/mp3/demo.mp3'; $file_size = filesize($full_path); header("Content-type:audio/mpeg"); header("Accept-Ranges:bytes"); header("Accept-Length:$file_size"); header("Content-Disposition:attachment;filename=demo.mp3"); readfile($full_path); exit(); }
客户端:
function down_mp3($url, $data){
       // curl下载文件
        $ch = curl_init();
       
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);       
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $mp3 = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno'.curl_error($ch);
        }
        
        curl_close($ch);
        // 保存文件到指定路径
        file_put_contents("f:/voice/test.mp3" , $mp3);

        unset($mp3);
}

 

posted @ 2018-03-28 09:53  love/coder  阅读(4651)  评论(0编辑  收藏  举报