Form and process file and String data at the same time with Spring Boot + Java

Now that I know how to send a Form and a String type at the same time, I will leave it as a memorandum.

Image of what you want to achieve

There is a form like this, and when you click the submit button, the page is updated with the updated information and an alert is displayed

スクリーンショット 2021-01-01 19.31.45.png スクリーンショット 2021-01-01 19.36.02.png

<form th:action="@{/portfolio/user/modify}" method="post" enctype="multipart/form-data">
          <table class="table table-hover table-bordered table-responsive-md text-center" th:object="${user}">
            <tr>
              <th scope="row" class="img-column">Profile Picture</th>
              <td style="position: relative;">
                <img th:src="${'data:image/png;base64,'+image}"
                  th:class="${user.getUserImg().length == 0 ? 'hidden' : 'mypage-img'}">
                <img src="/img/avator.png " alt="" th:class="${user.getUserImg().length == 0 ? 'mypage-img' : 'hidden'}">
                <label id="file-btn" for="userImg" class="bg-primary text-white">Choose your photo</label>
                <input type="file" name="file" id="userImg" style="display: none;">
                <p id="selected-status" class="mt-1">[Not yet selcted]</p>
              </td>
            </tr>
            <!--Of String<input>Is omitted-->
            <button id="cancel-btn" class="btn btn-warning hidden" type="button">Cancel</button>
            <button id="submit-btn" class="btn btn-primary hidden" type="submit">Submit</button>
          </div>
        </form>
// @Controller
@PostMapping(value = "/modify", consumes = { "multipart/form-data" }) //Point 1: 「consumes = { "multipart/form-data" }Added
  public String modify(UserForm userForm, @RequestPart("file") MultipartFile file, Model m) { //Point 2: 「@Added "Request Part" *@Not RequestParam
    userService.update(userForm, file, loginSession.getUserId());
    User user = userService.findByUserId(loginSession.getUserId());
    userService.setLoginSession(user);
    m.addAttribute("user", user);
    Boolean completeMsg = true;
    m.addAttribute("completeMsg", completeMsg);
    return "mypage";
  }
 // @Service
  public User findByUserNameAndPassword(String userName, String password) {
    return userRepos.findByUserNameAndPassword(userName, password);
  }
  //Overwrite user table
  public int update(UserForm userForm, MultipartFile file, Integer userId) {
    String userName = userForm.getUserName();
    String familyName = userForm.getFamilyName();
    String firstName = userForm.getFirstName();
    String email = userForm.getEmail();
    String password = userForm.getPassword();
    String imgPath = "/img/user/" + file.getOriginalFilename();
    return userRepos.update(userName, familyName, firstName, email, password, imgPath, userId);
  }

 /*Initialization of correction completion dialog*/
      var dialog = bootbox.dialog({
        message: '<p class="text-center mb-0">Your profile picture has changed</p>',
        backdrop: true,
        centerVertical: true,
        show: false
      });

      /*Alert display after updating user information*/
      const completeMsg = /*[[${completeMsg}]]*/ ''; //Point 3:Display an alert using the one passed to Create an instance of Boolean during the user information update process.
      console.log("completeMsg : " + completeMsg);
      if (completeMsg) {
        dialog.modal('show');
      }

Recommended Posts

Form and process file and String data at the same time with Spring Boot + Java
[Spring Boot] POST file array / list and other data at the same time [Axios]
[Spring Boot] Post files and other data at the same time [Axios]
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Form and process file and String data at the same time with Spring Boot + Java
How to achieve file upload with Feign
Android development-WEB access (POST) Try to communicate with the outside and send data. ~
I tried to implement file upload with Spring MVC
Create API to send and receive Json data in Spring
Draw a bar graph and a line graph at the same time with MPAndroidChart
File upload with Spring Boot
Set the date and time from the character string with POI
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
[Java] Method call error when inheritance and interface implementation are performed at the same time
How to use the same Mapper class in multiple data sources with Spring Boot + MyBatis
Access Web API on Android with Get and process Json (Java for the time being)
Check the actual date and time at parse with Java's SimpleDateFormat
Read the file under the classpath as a character string with spring
Setting to start multiple units at the same time with Vagrant
Compare Hello, world! In Spring Boot with Java, Kotlin and Groovy
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
See the behavior of entity update with Spring Boot + Spring Data JPA
[Java] LINE integration with Spring Boot
Overwrite upload of file with the same name with BOX SDK (java)
For the time being, run the war file delivered in Java with Docker
Beginners create web applications with Java and MySQL (adding at any time)
[Java] Create a jar file with both compressed and uncompressed with the jar command
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)
Processing at application startup with Spring Boot
Spring with Kotorin --2 RestController and Data Class
HTTPS with Spring Boot and Let's Encrypt
[Java 7] Divide the Java list and execute the process
[Java8] Search the directory and get the file
Form class validation test with Spring Boot
Monitor the Docker container and SystemD process on the same host with Zabbix on Ubuntu.
Read the file under the classpath as a character string with spring
Sample to batch process data on DB with Apache Camel Spring Boot starters
[Ruby] Define the hierarchy at the same time as Hash initialization with tap method
Parse the date and time string formatted by the C asctime function in Java
Until data acquisition with Spring Boot + MyBatis + PostgreSQL
Read a string in a PDF file with Java
[Java] Set the time from the browser with jsoup
[Java] The confusing part of String and StringBuilder
[2018 definitive edition] [Java 11 containerization] After downsizing the Spring Boot application to the limit, build it with Jib and push it to ECR
[Java / Spring Boot] Spring security ④ --Implementation of login process
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
[Java] Article to add validation with Spring Boot 2.3.1.
[Spring Boot] How to refer to the property file
[Java] Convert and import file values with OpenCSV
How to delete the tweet associated with the user when you delete it at the same time
Behavior noticed when adding RadioButton and initial check at the same time in code
Going back to the beginning and getting started with Java ① Data types and access modifiers
Error handling when the maximum file size is exceeded when uploading a file with Spring Boot
How to delete child elements associated with a parent element at the same time
Check the behavior of getOne, findById, and query methods in Spring Boot + Spring Data JPA
Spring Boot Form
Create a portfolio app using Java and Spring Boot
<java> Read Zip file and convert directly to string
Try using DI container with Laravel and Spring Boot
[Note] Configuration file when using Logback with Spring Boot
Switch environment with Spring Boot application.properties and @Profile annotation
[Java] [Spring Boot] Specify runtime profile --Spring Boot starting with NetBeans
Compatibility of Spring JDBC and MyBatis with Spring Data JDBC (provisional)
Spring Security usage memo: Cooperation with Spring MVC and Boot
Spring Boot with Spring Security Filter settings and addictive points