首先建一个叫做utils的文件夹里面建两个Java文件,一个叫Download,一个叫DownloadException
Download:
package com.todod.backend.module.basicInfo.security.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import com.alibaba.nacos.common.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
public class Download {
private static Logger log = LoggerFactory.getLogger(Download.class);
/**
* 生成随机文件名
*
* @param fileName
* @return
*/
public static String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(10000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate + random + extension;
}
/**
* 把文件推到前台浏览器
*/
public static void download(HttpServletRequest request, HttpServletResponse response, InputStream is,
String originalName) {
OutputStream out = null;
try {
setResponseHeader(request, response, originalName);
out = response.getOutputStream();
FileCopyUtils.copy(is, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* @Title: download
* @Description: 根据路径下载
* @author:gsh
* @date: 2019年4月30日
* @param request
* @param response
* @param abstractPath
* @param originalName
* @throws DownLoadException
* @return void
*/
public static void download(HttpServletRequest request, HttpServletResponse response, String abstractPath,
String originalName) throws DownLoadException {
OutputStream out = null;
InputStream is = null;
try {
is = new FileInputStream(abstractPath);
setResponseHeader(request, response, originalName);
out = response.getOutputStream();
FileCopyUtils.copy(is, out);
out.flush();
} catch (Exception e) {
log.error("下载异常", e);
e.printStackTrace();
throw new DownLoadException();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* @Title: setResponseHeader
* @Description: 设置响应头
* @author:gsh
* @date: 2019年4月30日
* @param request
* @param response
* @param originalName
* @return void
*/
public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response,
String originalName) {
try {
originalName = originalName.replaceAll("\\s", "+"); // 空间名有空格,ff下载会自动截图
String agent = request.getHeader("USER-AGENT");
String downloadName;
if (StringUtils.contains(agent, "MSIE") || StringUtils.contains(agent, "Trident")) // IE
{
downloadName = URLEncoder.encode(originalName, "UTF-8");
} else if (StringUtils.contains(agent, "Mozilla")) // 其它
{
downloadName = new String(originalName.getBytes("UTF-8"), "ISO-8859-1");
} else {
downloadName = URLEncoder.encode(originalName, "UTF-8");
}
response.setHeader("Location", downloadName);
response.setHeader("Content-Disposition", "attachment; filename=" + downloadName); // attachment下载;disposition在线浏览
} catch (Exception e) {
e.printStackTrace();
}
}
}
DownloadException:
package com.todod.backend.module.basicInfo.security.utils;
/**
* 下载异常
*
* @author gsh
* @version 创建时间:2019年4月30日 下午2:30:19
*
*/
public class DownLoadException extends Exception {
/**
* @Fields field:field:
*/
private static final long serialVersionUID = -2479623121635198L;
public DownLoadException() {
super();
}
public DownLoadException(String message) {
super(message);
}
}
在resources下建立static文件夹,再在static文件夹下建立file文件夹,把写好的Excel文件放进去就可以,类似这样
Controller层
@GetMapping("/get-import-template")
@Operation(summary = "获得导入宗教信仰信息模板")
public ModelAndView importTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = "static/file/belief.xlsx";
URL excelUrl = getClass().getClassLoader().getResource(path);
File excelFile = new File(excelUrl.getFile());
FileInputStream is = new FileInputStream(excelFile);
Download.download(request, response, is, "宗教信仰信息导入模板.xlsx");
return null;
}
记得改成自己的实体类和文件路径。