开发时有时需要下载文件,如生成excel文件等,在下载过程中需要加上动画或loading效果,由于jquery的ajax返回数据类型不支持二进制,但是原生的js是可以支持返回二进制数据的,所有需要封装ajax下载方法。/**
* ajax 下载文件
* @param url 文件生成地址,在浏览器生成文件即header保存文件
* @param data 其它数据
* @param file_name 文件名称,省略则读取 header 的Content-Disposition 内容
*/
function exportFile(url, data, file_name) {
let index = layer.load(0, {shade: false}); //0代表加载的风格,支持0-2
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.responseType = 'blob';
//xhr.setRequestHeader("If-Modified-Since", 0);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");//open()的后面
xhr.setRequestHeader("X-CSRF-TOKEN", $('meta[name="csrf-token"]').attr('content'));//open()的后面
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
layer.msg('开始下载...', {
offset: '15px'
, icon: 1
, time: 1000
});
//file_name: "attachment;filename="鲁南制药技术组.xlsx""
let file_name2 = xhr.getResponseHeader('Content-Disposition');
let file_name3 = decodeURI(file_name2).match(/"(.*)"/);
file_name = file_name || file_name3[1];
download(xhr.response, file_name, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} else {
layer.msg('下载失败,请重试', {
offset: '15px'
, icon: 2
, time: 3000
});
}
layer.close(index);
};
}
php在浏览器生成excel/**
* 生成文件,不保存,浏览器直接下载
* @param string $filename
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public function generateFile(string $filename = 'centphp.com测试')
{
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'centphp测试');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ''Xlsx'');
$objWriter->save('php://output');
exit;
}