public void downPrintFile(String fileName, InputStream is, HttpServletRequest request, HttpServletResponse response) {
try (
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())
) {
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0) || ((agent.contains("RV")) && (!agent.contains("FIREFOX"))))
fileName = URLEncoder.encode(fileName, "UTF-8");
else {
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
System.out.println("success");
bos.flush();
} catch (Exception e) {
System.out.println("附件下载失败!");
}
}
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
String fileName = "导入模板.xlsx";
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream;charset=utf-8");
String userAgent = request.getHeader("User-Agent");
String formFileName=fileName;
try {
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
formFileName = java.net.URLEncoder.encode(formFileName, String.valueOf(StandardCharsets.UTF_8));
} else {
formFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;filename=" + formFileName);
String filePath = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath() + fileName;
logger.info("导入模板的filePath=========》" + filePath);
File file = new File(filePath);
if (!file.exists()) {
throw new BusinessException("下载失败,模板未找到!");
}
try (
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is)) {
byte[] buff = new byte[1024];
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (FileNotFoundException e1) {
throw new BusinessException("模板未找到!");
} catch (IOException e) {
throw new BusinessException("模板下载失败!");
}
}
const a = document.createElement('a');
a.style.display = 'none';
a.download = '导入模板.xlsx';
a.href = '/api/attachDownload/downloadTemplate';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);