[JAVA] I tried to implement file upload with Spring MVC

Easy to do!

Should be. It's surprisingly easy to get there. It seems that you can go this way from Spring 4 for the time being.

Turn on the dispatcher and Servlet file upload features.

Spring uses an object called "MultipartFile" when uploading files. Let's turn this setting on in Spring and Servlet

Let's set web.xml and application-config.xml (xml with Bean settings).

First of all, the dispatcher's multipart file Specify the upload size. The last item is the size of the temporary files that the server saves. It seems better to specify something explicitly.

web.xml


  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/mvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--File upload mode-->
    <multipart-config>
    	<max-file-size>5242880</max-file-size>
    	<max-request-size>5242880</max-request-size>
    	<file-size-threshold>0</file-size-threshold>
    </multipart-config>
  </servlet>


And now Spring can handle multipart files. Let's add Multipart Resolver to the bean.

application-config.xml


    
     <!--File upload resolver-->   
    <bean id="multipartResolver"
		 class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
	</bean>

It's easy here.

Make the view side.

Let's create an upload page! When uploading a file, set ** enctype = "multipart / form-data ** in form.

My source is

  1. I'm using Spring Security, so I'm using the <form: form> tag
  2. Since I am using the upload form, the feature is that ** modelAttribute ** is specified.

The rest is not that special source. (Of course jsp)

ImageUpload.html


<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<head>
<meta content="ja" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Please enter your favorite sea or water image</title>
</head>

<body>

<form:form action="imageComplete"  method="post"
modelAttribute="ImageUploadForm" enctype="multipart/form-data">
Enter your favorite sea or water image! > <
	<input name="image" type="file" />
	
	<input name="submit" type="submit">
</form:form>

</body>

</html>

This is the upload form received by the server side

ImageUploadForm.java



import lombok.Data;

/**
 *Registration form
 * @author nozawa
 *
 */
@Data
public class ImageUploadForm {
	@NotNull
	private MultipartFile image;
}

Make a controller on the server side.

Now let's create a server side that receives the uploaded images.

First, enable the upload form.

ImageIOController.java



@Controller
public class ImageIOController {

	@ModelAttribute(name = "ImageUploadForm")
	public ImageUploadForm initForm(){
		ImageUploadForm imageUploadForm = new ImageUploadForm();
		/*
Initial setting
		*/
		return imageUploadForm;
	}
}

Next, create a method to display the upload screen.

ImageIOController.java



	@RequestMapping(value = "/imageUpload", method = RequestMethod.GET)
	public ModelAndView imageUpload() {
		ModelAndView mv = new ModelAndView("ImageUpload");
		return mv;
	}

This is the main. Make a part to receive the image. All you have to do is specify the upload form as an argument! It's super easy.

ImageIOController.java


	@RequestMapping(value = "/imageComplete", method = RequestMethod.POST)
	public ModelAndView imageUploadComplete(ImageUploadForm imageUploadForm) {
		System.out.println(imageUploadForm.getImage().getOriginalFilename());
		
		Integer FileSize = (int) (imageUploadForm.getImage().getSize());
		
		byte[] ImageBinary = new byte[FileSize];
		
		try {
			 ImageBinary = imageUploadForm.getImage().getBytes();
		} catch (IOException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}
		
		ModelAndView mv = new ModelAndView("ImageComplete");
		return mv;
	}

The MultipartFile object in the upload form is They are accessing temporary files that exist on the server. You can also get binary data properly ヾ (.> ﹏ <.) ノ

The whole controller looks like this

ImageIOController.java


package com.TsugaruInfo.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

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

import com.TsugaruInfo.formmodel.ImageUploadForm;
import com.TsugaruInfo.formmodel.RegisterForm;

@Controller
public class ImageIOController {

	@ModelAttribute(name = "ImageUploadForm")
	public ImageUploadForm initForm(){
		ImageUploadForm imageUploadForm = new ImageUploadForm();
		/*
Initial setting
		*/
		return imageUploadForm;
	}
	
	@RequestMapping(value = "/imageUpload", method = RequestMethod.GET)
	public ModelAndView imageUpload() {
		ModelAndView mv = new ModelAndView("ImageUpload");
		return mv;
	}
	
	@RequestMapping(value = "/imageComplete", method = RequestMethod.POST)
	public ModelAndView imageUploadComplete(ImageUploadForm imageUploadForm) {
		System.out.println(imageUploadForm.getImage().getOriginalFilename());
		
		Integer FileSize = (int) (imageUploadForm.getImage().getSize());
		
		byte[] ImageBinary = new byte[FileSize];
		
		try {
			 ImageBinary = imageUploadForm.getImage().getBytes();
		} catch (IOException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}
		
		ModelAndView mv = new ModelAndView("ImageComplete");
		return mv;
	}
}

Run

Let's run it

First open the upload screen image.png

Select an image and send it!

Let's take a look at the console.

image.png

I think the server is reading the file name properly.:. ゜ ヽ (´∀`.) ノ ゜.:. ゜

reference 5.17. File upload https://terasolunaorg.github.io/guideline/public_review/ArchitectureInDetail/FileUpload.html

Recommended Posts

I tried to implement file upload with Spring MVC
Implement file download with Spring MVC
I tried to implement ModanShogi with Kinx
How to realize huge file upload with TERASOLUNA 5.x (= Spring MVC)
I tried connecting to MySQL using JDBC Template with Spring MVC
File upload with Spring Boot
I tried to implement TCP / IP + BIO with JAVA
I tried to get started with Spring Data JPA
I tried to implement Stalin sort with Java Collector
I tried to interact with Java
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
[Rails] I tried to implement batch processing with Rake task
I tried to get started with Swagger using Spring Boot
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)
I tried to get started with WebAssembly
I tried to implement the image preview function with Rails / jQuery
I tried to create a Spring MVC development environment on Mac
I tried to implement flexible OR mapping with MyBatis Dynamic SQL
I tried Spring.
I tried to implement the Iterator pattern
I tried to make an Android application with MVC now (Java)
I tried Lazy Initialization with Spring Boot 2.2.0
Implement image input / output with Spring MVC
How to achieve file upload with Feign
How to realize huge file upload with Rest Template of Spring
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image
I tried to make Basic authentication with Java
I tried to implement polymorphic related in Nogizaka.
I tried to manage struts configuration with Coggle
I tried to manage login information with JMX
I tried to implement deep learning in Java
Try to implement login function with Spring Boot
I tried to link JavaFX and Spring Framework.
I wanted to gradle spring boot with multi-project
I tried to implement a server using Netty
I tried to break a block with java (1)
I tried Spring Batch
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
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)
How to create an Excel form using a template file with Spring MVC
I tried to clone a web application full of bugs with Spring Boot
I tried to read and output CSV with Outsystems
I tried to implement Firebase push notification in Java
[Java 11] I tried to execute Java without compiling with javac
05. I tried to stub the source of Spring Boot
I started MySQL 5.7 with docker-compose and tried to connect
I tried to reduce the capacity of Spring Boot
I want to monitor a specific file with WatchService
I tried to draw animation with Blazor + canvas API
I tried OCR processing a PDF file with Java
How to test file upload screen in Spring + Selenium
[Java] I tried to implement Yahoo API product search
I tried to implement the Euclidean algorithm in Java
File upload with Spring Boot (do not use Multipart File)
roman numerals (I tried to simplify it with hash)
I tried to create a shopping site administrator function / screen with Java and Spring
[Swift] I tried to implement Instagram profile-like UI with UICollectionView only with code without storyboard