解決 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;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章