LoginSignup
1
0

More than 1 year has passed since last update.

Javaのシステムで画像を取り扱う方法

Last updated at Posted at 2021-11-29

まずはJSPのformで下記を追記します。

enctype="multipart/form-data"

こんな風になります。

<form action="" method="POST" enctype="multipart/form-data">

インプットタグはタイプをfileにします。

<div class="tr">
	<label for="logo">画像:</label>
	<div class="td">
		<input type="file" id="logo" name="logo">
	</div>
</div>

JSPは以上です。

サーブレットでは以下の記述をアノテーションのすぐ下に追記します。

@MultipartConfig(
	maxFileSize=10000000,
	maxRequestSize=10000000,
	fileSizeThreshold=10000000
)

画像データの取り込み部分

// 画像のファイル名取得
Part part = request.getPart("logo");
String logo = Paths.get(part.getSubmittedFileName()).getFileName().toString();
String logo_name = logo.isEmpty() ? "" : logo;

logo_nameは文字列としてDBに保存します。画像ファイルそのものは新しく作ったフォルダに保存します。
まずWEB-INFと同じディレクトリに空のフォルダを作ります。(ここではlogoという名前でフォルダを作ります。)

次に以下のコードで記述します。

// 画像アップロード
String path = getServletContext().getRealPath("/logo");
part.write(path + File.separator + logo_name);

以上で画像データの保存はできました。
保存した画像データの表示は以下の記述でできます。

<img src="/コンテキストルート/logo/DBに保存したlogo_nameの文字列">
1
0
0

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
0