springboot 下载静态模板文件

需求:页面直接访问下载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();
    } 

原文链接:https://www.cnblogs.com/djq-jone/p/10737946.html

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值