springbootプロジェクトがパッケージ化されてLinuxシステムにデプロイされ、ダウンロードリソース/静的/静的リソースが見つからないという問題を解決します

springbootプロジェクトがパッケージ化されてLinuxシステムにデプロイされ、ダウンロードリソース/静的/静的リソースが見つからないという問題を解決します

spingbootを使用して開発し、構成ファイルをプロジェクトのルートディレクトリに追加し、IDEのthis.getClass()。getResource( "")を介して問題なくファイルパスを取得します。
jarとして実行した後、ファイルを読み取ることができなくなります。jar内の対応するクラスパスにファイルが表示され、にパッケージ化されていることを確認できます。

現時点では、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