0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

springの画像処理

Posted at

springとhtmlを使用して画像の表示、保存、格納がしたい

やりたいこと

  1. 選択された画像のオリジナルネームにし、DBに格納   結果:OK

  2. 選択された画像を指定のパスに保存           結果:OK

  3. 1番2番で行った値をもとにHTMLで表示        結果:NG

※以下は現時点での進捗です。

新規で写真追加の場合

newphoto.html
<form id="uploadForm">
            <tr>
                <input type="file" id="fileUpload" name="facePhoto" onchange="uploadImage()">
            </tr>
        </form>
<script>
    function uploadImage() {
        var formData = new FormData(document.getElementById('uploadForm'));
        fetch('/uploadpicture', { method: 'POST', body: formData })}
</script>
Controller.java
@PostMapping("/uploadpicture")
	public void uploadImage(@RequestParam("facePhoto") MultipartFile multipartFile) throws Exception {
		byte[] bytes = multipartFile.getBytes();
		String pathfile = multipartFile.getOriginalFilename();
		Path path = Paths.get("C:\\Users\\name\\OneDrive\\デスクトップ\\facePhoto", pathfile );
		session.setAttribute("pathfile", pathfile);
		Files.write(path, bytes);
	}

@PostMapping("/nuwphoto") //こちらには他の値もありますが今回関係ないので省略//
        facephoto = (String) session.getAttribute("pathfile");
		session.removeAttribute("pathfile");
		if (facephoto != null && !facephoto.isEmpty()) {
			filePath = facephoto;
		} else {
			filePath = null;
		}
    Photo.save(new Photo(filePath)
photo.html
   <form id="uploadForm">
              <img th:src="'/img/' + ${indiv2.facePhoto}" width="80px" height="80px" >
    </form>

    <script>
        function uploadImage() {
            var formData = new FormData(document.getElementById('uploadForm'));
            fetch('/uploadphoto', { method: 'POST', body: formData })
        }
    </script>

流れ

  1. newphoto.htmlで画像を選択し、選択された画像をuploadpictureに送る

  2. Controller.javaで選択された画像を指定のフォルダーに格納&オリジナルネームを作成後DBに格納

  3. photo.htmlで指定した画像を表示(<img th:src="'/facePhoto/' + ${indiv2.facePhoto}"))indiv2は関連したDBの値を引っ張ってきてますので ${indiv2.facePhoto}の中身にはオリジナルネームが入っております。

##エラー
画像の格納、オリジナルネームの保存はできておりますが、表示の部分がアイコンだけになってしまいます。

考えられる理由:指定しているファイルパスが"C:\Users\name\OneDrive\デスクトップ\facePhoto"がデスクトップのため、
今回はアプリを重くしないためプロジェクトの外に作りました

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?