需求:页面直接访问下载Excel模板
问题:
在本地使用getClass().getResource("/templates/"+fileName).getPath()获取的是系统正确的路径,而springboot应用打包成jar放到服务端后 获取的路径是
bootdo.jar!/BOOT-INF/classes!//templates/template.xlsx,所以下载出来的模板文件是错误的,会报如下错误:
java.io.FileNotFoundException: file:bootdo.jar!/BOOT-INF/classes!/templates/template.xlsx (No such file or directory)
页面代码:
<form class="form-horizontal m-t" id="signupForm">
<div class="form-group">
<label class="col-sm-3 control-label">
</label>
<div class="col-sm-8">
<span class="columns col-md-8 col-sm-8 col-xs-8 nopadding">支持扩展名:.xlsx .xls<a style="color: blue;" class="text-center" href="#" download="" onclick="downloadExcel()">下载模板</a></span>
</div>
</div>
</div>
</form>
js代码:
function downloadExcel(){
window.location.href ='/operation/nterpriseSettJnl/downloadExcel';
}
后端代码:
@Log("下载模板文件")
@GetMapping( "/downloadExcel")
public void downloadExcel(HttpServletResponse response,HttpServletRequest request){
String path = "/templates/template.xlsx" ;
String fileName = path.substring(path.lastIndexOf("/") + 1);
try {
downloadExcel(response, path, fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//下载excel模板
public void downloadExcel(HttpServletResponse response, String path, String fileName) throws IOException {
/** 将文件名称进行编码 */
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("content-type:octet-stream");
/** 读取服务器端模板文件*/
InputStream inputStream = PayEnterpriseSettJnlController.class.getResourceAsStream(path);
/** 将流中内容写出去 .*/
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
}