[JAVA] Just input and output images with Spring MVC

Notes

Created as a sample because there was a request to upload an image using SpringMVC and output it. It's just a sample level, so I'm ignoring Validation and not checking the extension. I can upload images, but I haven't saved them. For those who want to do it for the time being.

Execution environment

The execution environment is as follows

name Version etc.
IDE sts-4.0.1.RELEASE
Java Java1.8
SpringFrameworkBoot 2.1.9
SpringDependencyManagement 1.0.8

Flow of operation

The sample to be created can be classified as follows (excluding the FirstApplication class)

① HTML for uploading images ② Form to store image data ③ Controller for passing image data ④ HTML to display the uploaded image

Actual code

Html corresponding to ①

upload.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8" />
    <title>upload.html</title>
</head>

<body>
    <!--Note that if you do not set enctype in form, the contents of the image will not be sent.-->
    <form th:action="@{/upload}" th:object="${imageForm}" method="post" enctype="multipart/form-data">
Select files:<input type="file" th:field="*{image}" /><br /> <input type="submit" value="Send" />
    </form>
</body>

</html>

The point is `ʻenc type =" multipart / form-data "`` Without this, the controller will not be able to receive the data inside (only the file name will be received)

Form corresponding to ②

imageForm.java


package com.practice.demo_spring.web;

import org.springframework.web.multipart.MultipartFile;

public class ImageForm {

	private MultipartFile image;

	public MultipartFile getImage() {
		return image;
	}

	public void setImage(MultipartFile image) {
		this.image = image;
	}

}

A form class that never happens.

Controller corresponding to ③

UploadController.java


package com.practice.demo_spring.web;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UploadController {
	
	@ModelAttribute
	public ImageForm setForm() {
		return new ImageForm();
	}
	
	/**
	 *First localhost:8080/upload with first.Set to access html
	 * @return upload.html
	 */
	@RequestMapping("/first")
	public String first() {
		return "upload";
	}
	
	
	/**
	 *Get the uploaded image data and encode it with base64
	 *Change the encoded one to a string(At the same time, specify the extension as jpeg here.)And pass it to the next html
	 * @param imageForm Uploaded data
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/upload")
	public String upload(ImageForm imageForm, Model model) throws Exception {
		System.out.println(imageForm.getImage().getSize());
		StringBuffer data = new StringBuffer();
		String base64 = new String(Base64.encodeBase64(imageForm.getImage().getBytes()),"ASCII");
		data.append("data:image/jpeg;base64,");
		data.append(base64);
		model.addAttribute("base64image",data.toString());
		return "express";
	}

}

As a process, (1) Get the image data stored in imageForm and make it an array of bytes ② Encode it to base64 and change it to String type ③ Combine the previously changed String with "data: image / jpeg; base64," to make it a form that can be specified with <img ht: src = "">. Following the above flow

Html corresponding to ④

express.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>express.html</title>
  </head>
  <body>
The image is<img th:src="${base64image}"/>is
  </body>
</html>

Here, the character string received from the controller class is specified in src and displayed.

demo

Go to https: // localhost: 8080 / first 2019-10-17_10h42_20.png

Select image data appropriately 2019-10-17_11h00_26.png

By pressing the send button, the uploaded image will be displayed. 2019-10-17_11h01_09.png

For the time being, I created only a sample. After that, please add a check or some function as you like.

Recommended Posts

Just input and output images with Spring MVC
Implement image input / output with Spring MVC
[Beginner] Upload images and files with Spring [Self-satisfaction]
Spring Security usage memo: Cooperation with Spring MVC and Boot
Java Config with Spring MVC
Implement file download with Spring MVC
Output PDF and TIFF with Java 8
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
Spring with Kotorin --2 RestController and Data Class
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
I want to display images with REST Controller of Java and Spring!
HTTPS with Spring Boot and Let's Encrypt
I tried printing a form with Spring MVC and JasperReports Extra edition (Variables edition)
I tried printing a form with Spring MVC and JasperReports Extra edition (image edition)
Let's write Java file input / output with NIO
Test controller with Mock MVC in Spring Boot
[Java] How to get and output standard input
Output request and response log in Spring Boot
Periodically update DB with Spring Batch and MyBatis
Request parameter log output sample Java & Spring MVC
Get detailed statistics and edit output with Locust
Try using DI container with Laravel and Spring Boot
I tried to implement file upload with Spring MVC
Switch environment with Spring Boot application.properties and @Profile annotation
I tried to read and output CSV with Outsystems
Compatibility of Spring JDBC and MyBatis with Spring Data JDBC (provisional)
Extract face images from videos with ffmpeg and OpenVINO
Spring Boot with Spring Security Filter settings and addictive points
Attempt to SSR Vue.js with Spring Boot and GraalJS
Connect Spring Boot and Angular type-safely with OpenAPI Generator
Output vector graphics images (PDF, SVG, PPT, EPS, SWF) with Java Graphics 2D and various libraries