動態提交使用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;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM