動態提交使用jQuery 完成ajax 檔案下載----後端php

來源:互聯網
上載者:User

標籤:

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

 

 

動態提交使用jQuery 完成ajax 檔案下載----後端php

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.