js实现前端下载功能
前端代码
html代码
<div class="div_button_btn_span">
<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="exportExcel()" plain="true">导出明细</a>
</div>
js代码
function exportExcel() {
// 定义要发送的参数
let postData = $("#searchForm").serializeObject();
// 发送 POST 请求
fetch('${ctxPO}/url/PosInvoiceUrlController/exportPosInvoice', {
method: 'POST',
body: JSON.stringify(postData),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = '供应商发票.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
如果需需要则个名称期望是从后端获取的,可以从Content-disposition
中获取
服务端代码
/**
* 导出发票数据
* @param condition 条件
* @param response 响应
*/
@RequestMapping("exportPosInvoice")
public void exportPosInvoice(PosInvoiceListQueryCondition condition, HttpServletResponse response){
try {
Workbook workbook = posInvoiceService.createExportPosInvoiceExcel(condition);
/****************Excle表格渲染完成后,开始返回流数据*****************/
/**设置头信息*/
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
/**一定要设置成xlsx格式*/
response.setHeader("Content-disposition", "attachment;filename=供应商发票.xlsx");
/**创建一个输出流*/
ServletOutputStream outputStream = response.getOutputStream();
/**写入数据*/
workbook.write(outputStream);
/**关闭流*/
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
其中 Workbook workbook = posInvoiceService.createExportPosInvoiceExcel(condition)
是生成excel代码,此处不过多罗列了
如果是文件URL的无需后端生成的,可以直接参考以下代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Download</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="downloadBtn">Download File</button>
<script>
$(document).ready(function() {
$('#downloadBtn').click(function() {
var fileUrl = 'path/to/your/file.pdf'; // 替换为实际文件路径
downloadFile(fileUrl);
});
function downloadFile(fileUrl) {
// 创建一个隐藏的<a>标签
var link = document.createElement('a');
link.href = fileUrl;
link.download = fileUrl.substr(fileUrl.lastIndexOf('/') + 1); // 设置下载文件的名称
link.style.display = 'none';
document.body.appendChild(link);
// 模拟点击<a>标签来触发文件下载
link.click();
// 清理
document.body.removeChild(link);
}
});
</script>
</body>
</html>
如果是直接从下载文件,需要注意跨域问题