解决 springboot项目打包部署到linux系统下,下载resources/static/静态资源找不到的问题

解决 springboot项目打包部署到linux系统下,下载resources/static/静态资源找不到的问题

使用spingboot开发,在工程根目录中添加了一个配置文件,在IDE中通过this.getClass().getResource("")来获取文件的路径,没有任何的问题。
在打成jar后运行,结果不能读取到文件。在jar里面对应的class路径下可以看到该文件,确定是有打包进去的。

此时通过 this.getClass().getResource("");方法无法正确获取文件。

用 InputStream inputStream=this.getClass().getResourceAsStream(""); 可以正确读取。

干货

@ApiOperation(value = "下载数据模板", notes = "下载数据模板")
	@RequestMapping(value = "/downloadTemplates", method = RequestMethod.POST)
	public void downloadTemplates(HttpServletResponse response) {
    
    

		try {
    
    
			String path = "/static/template.xls";
			String fileName = path.substring(path.lastIndexOf("/") + 1);
			/** 读取服务器端模板文件 */
			InputStream inputStream = this.getClass().getResourceAsStream(path);
			
			/** 将文件名称进行编码 */
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
			response.setContentType("content-type:octet-stream");

			/** 将流中内容写出去 . */
			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();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return;
	}

猜你喜欢

转载自blog.csdn.net/ampsycho/article/details/103272453
今日推荐