File upload with Spring Boot

Implement as the title of the article. The following functions will be implemented this time. -Upload by specifying the image path from the input screen composed of HTML form and input tag -Output the file to the specified directory via Java

File to modify

Modify the following 3 files 1.png

Controller

java:com.example.SampleController.java


@RequestMapping(path = "/sample/upload", method = RequestMethod.GET)
String uploadview(Model model) {
  return "sample/upload";
}

@RequestMapping(path = "/sample/upload", method = RequestMethod.POST)
String upload(Model model, UploadForm uploadForm) {
  if (uploadForm.getFile().isEmpty()) {
    return "sample/upload";
  }

  // check upload distination directory.If there was no directory, make
  // func.
  Path path = Paths.get("/Users/demo-kusa/image");
  if (!Files.exists(path)) {
    try {
      Files.createDirectory(path);
    } catch (NoSuchFileException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }

  int dot = uploadForm.getFile().getOriginalFilename().lastIndexOf(".");
  String extention = "";
  if (dot > 0) {
    extention = uploadForm.getFile().getOriginalFilename().substring(dot).toLowerCase();
  }
  String filename = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());
  Path uploadfile = Paths
      .get("/Users/demo-kusa/image/" + filename + extention);

  try (OutputStream os = Files.newOutputStream(uploadfile, StandardOpenOption.CREATE)) {
    byte[] bytes = uploadForm.getFile().getBytes();
    os.write(bytes);
  } catch (IOException ex) {
    System.err.println(ex);
  }

  return "redirect:/sample";
}

ActionForm

java:com.example.UploadForm.java


package com.example;

import org.springframework.web.multipart.MultipartFile;
public class UploadForm {
  private MultipartFile file;

  public MultipartFile getFile() {
    return file;
  }

  public void setFile(MultipartFile file) {
    this.file = file;
  }
}

template

src/main/resources/templates/sample/upload.html


<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>top page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>Image upload</h2>
    <form method="post" enctype="multipart/form-data" action="/sample/upload" >
        <input name="file" type="file" />
        <input type="submit" value="Send"/>
    </form>
</body>
</html>

This article has partially replaced the environment-dependent part, but the source is below, so if you need it, please. github kaikusakari/spring_crud

Recommended Posts

File upload with Spring Boot
File upload with Spring Boot (do not use Multipart File)
Download with Spring Boot
Generate barcode with Spring Boot
Hello World with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
iOS: File upload with SFTP
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Create microservices with Spring Boot
Send email with spring boot
I tried to implement file upload with Spring MVC
[Note] Configuration file when using Logback with Spring Boot
Use Basic Authentication with Spring Boot
gRPC on Spring Boot with grpc-spring-boot-starter
Hot deploy with Spring Boot development
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
Implement file download with Spring MVC
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Extract SQL to property file with jdbcTemplate of spring boot
Processing at application startup with Spring Boot
What is a Spring Boot .original file?
Hello World with Eclipse + Spring Boot + Maven
How to realize huge file upload with TERASOLUNA 5.x (= Spring MVC)
Static file access priority in Spring boot
Send regular notifications with LineNotify + Spring Boot
Local file download memorandum in Spring Boot
Perform transaction confirmation test with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Challenge Spring Boot
Try using Spring Boot with VS Code
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
I tried Lazy Initialization with Spring Boot 2.2.0
Spring Boot Form
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async
Implement paging function with Spring Boot + Thymeleaf
Spring Boot Memorandum
gae + spring boot
(IntelliJ + gradle) Hello World with Spring Boot