动态提交使用jQuery 完成ajax 文件下载----后端php

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

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值