1、js代码

// Ajax 文件下载

//当不用传参时,可以将data去掉

jQuery.download = function(url, data, method){ // 获得url和data
    if( url && data ){
        // data 是 string 或者 array/object
        data = typeof data == 'string' ? data : jQuery.param(data); // 把参数组装成 form的 input
        var inputs = '';
        jQuery.each(data.split('&'), function(){
            var pair = this.split('=');
            inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
        }); // request发送请求
        jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>').appendTo('body').submit().remove();
    };
};

 

调用实例:

$.download('ExcelDownload.do','find=commoncode','post' );

 

2、php代码

/**
* 下载文件
* @param string $file
* 被下载文件的路径
* @param string $name
* 用户看到的文件名
*/
public function download(){
$file = "D:\\cloudwafSites.txt";
$name = 'test';
$fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);
$filePath = realpath($file);

$fp = fopen($filePath,'rb');

if(!$filePath || !$fp){
header('HTTP/1.1 404 Not Found');
echo "Error: 404 Not Found.(server file path error)";
exit;
}

$fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
$encoded_filename = urlencode($fileName);
$encoded_filename = str_replace("+", "%20", $encoded_filename);

header('HTTP/1.1 200 OK');
header( "Pragma: public" );
header( "Expires: 0" );
header("Content-type: application/octet-stream");
header("Content-Length: ".filesize($filePath));
header("Accept-Ranges: bytes");
header("Accept-Length: ".filesize($filePath));

$ua = $_SERVER["HTTP_USER_AGENT"];
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
} else {
header('Content-Disposition: attachment; filename="' . $fileName . '"');
}

//ob_end_clean(); //<--有些情况可能需要调用此函数
// 输出文件内容
fpassthru($fp);
exit;
}

 

 

posted on 2016-08-15 14:04  何石-博客  阅读(10620)  评论(0编辑  收藏  举报