spring boot ajax异步下载文件

原理:
1.异步生成文件,返回文件名。
2.触发a标签通过文件名下载

$.ajax({
	type : "GET",
	url : url,
	data : $("#queryForm").serialize(),
	dataType : "json",
	success : function(result){
		const link = document.createElement('a')
		link.href = "/tpatrol/downloadPatrol?fileName="+result.fileName
		link.click()
	}
});
/**
 * 下载文件
 * @param fileName   文件名称
 * @param response
 */
public void downloadPatrol(String fileName,HttpServletResponse response) {
	String path = filePath+fileName;
	File  file = new File(path);
	if (!file.exists()) {
		log.info("文件不存在,filePath={}",file);
		return;
	}
	
	FileInputStream fis = null;
	BufferedInputStream bis = null;
	try {
		response.setContentType("application/force-download");// 设置强制下载不打开            
		response.addHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode("文件名.xlsx", "UTF-8"));
		byte[] buffer = new byte[1024];
		fis = new FileInputStream(file);
		bis = new BufferedInputStream(fis);
		OutputStream outputStream = response.getOutputStream();
		int i = bis.read(buffer);
		while (i != -1) {
			outputStream.write(buffer, 0, i);
			i = bis.read(buffer);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

你可能感兴趣的:(javascript,java)