[JAVA] [Beginner] Upload images and files with Spring [Self-satisfaction]

environment

directory
.
└── _src
    └── _main
        ├── _java
        |   ├── _com.example.demo
        |       ├── FileUpdateController
        |       └── DemoApplication 
        └── _resources
            ├── _static
            |   ├── bootstrap.css
            |   ├── bootstrap.min.css
            |   └── training.css
            ├── _templates
            |   ├── uploadView.html
            |   └── uploadStatusView.html
            └── application.properties

Purpose

** Implement image and file upload function **

contents

pom.xml

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.assertj</groupId>
			<artifactId>assertj-core</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.properties

application.properties


spring.thymeleaf.mode=HTML
spring.datasource.url=jdbc:mysql://localhost:3306/DB name?autoReconnect=true&
useSSL=false&serverTimezone=JST
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.servlet.multipart.max-file-size=15MB
spring.servlet.multipart.max-request-size=15MB
Demo.application.java

Demo.application.java



package com.example.demo;

import com.example.demo.controller.FileUploadController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import java.io.File;

@SpringBootApplication
@ComponentScan({"com.example.demo", "controller"})
public class DemoApplication {

	public static void main(String[] args) {
		new File(FileUploadController.uploadDirectory).mkdir();
		SpringApplication.run(DemoApplication.class, args);
	}

}
FileUploadController.java

FileUploadController.java


package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileUploadController {
    public static String uploadDirectory = System.getProperty("user.dir")+"uploads";

    @RequestMapping("/")
    public String UploadPage(Model model){
        return "uploadView";

    }

    @RequestMapping("/upload")
    public String upload(Model model, @RequestParam("files") MultipartFile[] files){
        StringBuilder fileNames = new StringBuilder();
        for(MultipartFile file : files){
            Path fileNameAndPath = Paths.get(uploadDirectory, file.getOriginalFilename());
            fileNames.append(file.getOriginalFilename());
            try {
                Files.write(fileNameAndPath, file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("msg", "Successfully uploaded files "+ fileNames.toString());
        return "uploadStatusView";
    }
}

uploadView.html

uploadView.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>  
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="files" multiple>
        <input type="submit" value="Upload Files">
    </form>
    </body>
</html>
uploadStatusView.html

uploadStatusView.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:if="${msg}">
        <span th:text="${msg}"></span>
    </div>
    <div>
        <span><a href="/">Upload More</a></span>
    </div>
</body>
</html>

Source

You Tube

Recommended Posts

[Beginner] Upload images and files with Spring [Self-satisfaction]
Just input and output images with Spring MVC
[Java] Upload images and base64
Drag and drop files with JavaFX
[Java] Reading and writing files with OpenCSV
HTTPS with Spring Boot and Let's Encrypt
Delete folders and files with File Manager
Periodically update DB with Spring Batch and MyBatis
[Ruby on Rails] Upload multiple images with refile
[Review] Reading and writing files with java (JDK6)
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
Compatibility of Spring JDBC and MyBatis with Spring Data JDBC (provisional)
Spring Security usage memo: Cooperation with Spring MVC and Boot
Extract face images from videos with ffmpeg and OpenVINO
[Spring Boot] Get user information with Rest API (beginner)
Connect with port forwarding with SSH and send and receive files
Attempt to SSR Vue.js with Spring Boot and GraalJS
Connect Spring Boot and Angular type-safely with OpenAPI Generator
File upload with Spring Boot (do not use Multipart File)
[Java] Development with multiple files using package and import