LoginSignup
1
2

More than 1 year has passed since last update.

【SpringBoot】画像表示する2つの方法(1/2)

Last updated at Posted at 2021-04-05

#SpringBoot2で画像表示
今回は画像表示をやっていきます。
やり方としては2つあります。

①HTMLのimgタグを利用してサーバにリクエストを出し、画像データをレスポンスとして返す方法。

②画像データをBase64に変換しimgタグに直接埋め込む方法。

今回は①のほうでやっていきます。
②の方法は以下のリンクからどうぞ
SpringBoot2で画像表示する2つの方法(2/2)

##全体の流れ
①GETリクエストで画面にアクセス
②画面からResponseBodyにGETリクエストを送る
③画面に画像データをレスポンスする。

各ファイルの作成

####Controllerを作成する
Fileクラスに画像フォルダのディレクトリを指定しています。
画像をバイト列に変換しResponseHeaderに画像情報をセットしています。
その後バイト列にした画像、ヘッダー情報を送信しています。

ImageController
@Controller
public class ImageController {

	@GetMapping("/")
	public String getIndex() {
		return "image";
	}
	
	@RequestMapping("/getImg")
	@ResponseBody
	public HttpEntity<byte[]> getImg(@RequestParam("name") String fileName){
		File fileImg = new File("img/"+ fileName +".png");
		
		byte[] byteImg = null;
		HttpHeaders headers = null;
		try {
			//バイト列に変換
			byteImg = Files.readAllBytes(fileImg.toPath());
			headers = new HttpHeaders();
			
			//Responseのヘッダーを作成
			headers.setContentType(MediaType.IMAGE_PNG);
			headers.setContentLength(byteImg.length);
		}catch(IOException e) {
			return null;
		}
		return new HttpEntity<byte[]>(byteImg,headers);
	}
	
}

####htmlを作成する
src属性から上記ResponseBodyにリクエストを送ります。

image.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<title>画像表示</title>
</head>
<body>
	<p>画像表示</p>
	<img th:src="@{./getImg?name=testimg}">
</body>
</html>
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2