本文实例讲述了PHP使用ajax的post方式下载excel文件。分享给大家供大家参考,具体如下:
项目需求,前端发起ajax请求,后端生成excel并下载,同时需要在header头中,带上token验证信息,参考了很多文章,最终实现如下:
PHP后端使用base64:
1
2
3
4
5
6
7
|
$filename = 'demo.xlsx' ; $objWriter = \PHPExcel_IOFactory::createWriter( $objectPHPExcel , 'Excel2007' ); ob_start(); $objWriter ->save( "php://output" ); $xlsData = ob_get_contents(); ob_end_clean(); return Api::success([ 'filename' => $filename , 'file' => "data:application/vnd.ms-excel;base64," . base64_encode ( $xlsData )]); |
JS前端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
$( '.download' ).click( function (){ var url = "http://xxxx.com/group/bi/export" ; var params = { from_date: '2017-09-01' , to_date: '2017-09-08' , group_id: 1 }; $.ajax({ type: 'POST' , url: url, data: params, beforeSend: function (request) { request.setRequestHeader( "Authorization" , "token信息,验证身份" ); }, success: function (redata) { // 创建a标签,设置属性,并触发点击下载 var $a = $( "<a>" ); $a.attr( "href" , redata.data.file); $a.attr( "download" , redata.data.filename); $( "body" ).append($a); $a[0].click(); $a.remove(); } }); }); |
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://www.cnblogs.com/cqingt/p/7562002.html