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)

页面代码:

支持扩展名:.xlsx .xls下载模板

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

你可能感兴趣的:(springboot)