路径匹配-资源解析器
/**
* 下载文件
* @param filePath resource包下的称为classpath路径 /template/partyMemberInfo.xlsx
* @param fileNewName 给浏览器的名称
* @param response servlet响应流
* @throws IOException
*/
public static void downloadFile(String filePath, String fileNewName, HttpServletResponse response) throws IOException {
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource resource = resourcePatternResolver.getResource("classpath:"+filePath); // "/template/partyMemberInfo.xlsx"
// 临时路径
String fileTempPath = UtilFile.getTempDirectoryPath() + filePath;
// 复制到临时路径下 注:jar包中的文件无法直接通过file访问
FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(new File(fileTempPath)));
下载文件
fileName是显示给浏览器的
filePath是准备下载的路径(通过上面的路径匹配-资源解析器)
// response.setContentType("application/vnd.ms-excel;charset=UTF-8");
// response.setHeader("Pragma", "no-cache");
// response.setHeader("Cache-Control", "no-cache");
// 配置下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载正常显示中文 fixme 此处的fileName是显示给浏览器的
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileNewName.getBytes("UTF-8"), "iso8859-1"));
// 实现文件下载 fixme filePath代表的:路径+文件名 文件->输入流-缓存-> 输出流
// try-with-resource 必须是实现AutoCloseable的接口
try (FileInputStream fis = new FileInputStream(fileTempPath);
BufferedInputStream bis = new BufferedInputStream(fis);) {
byte[] buffer = new byte[1024];
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
} catch (Exception e) {
System.out.println("Download error: " + e.getMessage());
}