[JAVA] Uploading and downloading files using Ajax in Spring Boot (without JQuery)

Two things to make

  1. Upload the image with Ajax, store it on the server and display it
  2. Select the image to display and press the image display button to download with Ajax and display the image

Demo screen

image.png

1. File upload

--Screen side

imageajax.html (part)


<body>
	<h3>file upload</h3>

	<form id="imageFormId">
		<input type="file" name="inputFileName" />
		<button type="button" onclick="uploadImage('imageFormId', 'myUploadedImageId')">Image upload</button>
	</form>
	<img id="myUploadedImageId" style="width: 400px">

	<script>
		function uploadImage(imgForm, imgCtrl) {
			const formData = new FormData(document.getElementById(imgForm));
			const request = new XMLHttpRequest();
			request.onreadystatechange = function() {
				if (this.readyState == 4 && this.status == 200) {
					const img = document.getElementById(imgCtrl);
					const url = window.URL || window.webkitURL;
					//Display the response as an image
					img.src = url.createObjectURL(this.response);
				}
			}
			request.open("POST", "/uploadimage");
			request.responseType = 'blob';
			request.send(formData);
		}
	</script>
</body>

--Controller side

ImageAjaxController (part)


	/**
	 *file upload
	 */
	@PostMapping("/uploadimage")
	public ResponseEntity<byte[]> uploadImage(@RequestParam("inputFileName") final MultipartFile uploadFile) {

		if (uploadFile.isEmpty()) {
			return ResponseEntity.of(Optional.empty());
		}
		//Get Path to store uploaded files
		final Path path = Paths.get("c:/uploaddir", uploadFile.getOriginalFilename());

		final byte[] bytes;
		try {
			//Get the binary of the uploaded file
			bytes = uploadFile.getBytes();
			//File storage
			Files.write(path, bytes);
		} catch (IOException e) {
			return ResponseEntity.of(Optional.empty());
		}
		return ResponseEntity.ok(bytes);
	}

--The maximum file size to upload is 1MB, so to upload a larger size, set as follows.

application.yml


spring:
  servlet:
    multipart:
      max-file-size: 30MB
      max-request-size: 30MB

2. File selection

--Screen side

imageajax.html (part)


<body>
	<h3>File selection</h3>

	<select id="selectImageId">
		<option value="a">a</option>
		<option value="b">b</option>
	</select>
	<button type="button" onclick="displayImage('selectImageId', 'mySelectedImageId')">Image display</button>
	<img id="mySelectedImageId" style="width: 400px">

	<script>
		function displayImage(selectCtrl, imgCtrl) {
			const select = document.getElementById(selectCtrl);
			const request = new XMLHttpRequest();
			request.onreadystatechange = function() {
				if (this.readyState == 4 && this.status == 200) {
					const img = document.getElementById(imgCtrl);
					const url = window.URL || window.webkitURL;
					//Display the response as an image
					img.src = url.createObjectURL(this.response);
				}
			}
			//Send choices and get files
			request.open("GET", "/selectimage/" + select.value);
			request.responseType = 'blob';
			request.send();
		}
	</script>
</body>

--Controller side

ImageAjaxController (part)


	/**
	 *File selection
	 */
	@GetMapping("/selectimage/{selectNum}")
	public ResponseEntity<byte[]> getImage(@PathVariable final String selectNum) {

		//Get file name from choices
		final String fileName;
		switch (selectNum) {
		case "a":
			fileName = "a.jpg ";
			break;
		case "b":
			fileName = "b.jpg ";
			break;
		default:
			return ResponseEntity.of(Optional.empty());
		}

		//File Path
		final Path path = Paths.get("c:/selectdir", fileName);

		final byte[] bytes;
		try {
			//Read the file
			bytes = Files.readAllBytes(path);
		} catch (IOException e) {
			return ResponseEntity.of(Optional.empty());
		}
		return ResponseEntity.ok(bytes);
	}

Recommended Posts

Uploading and downloading files using Ajax in Spring Boot (without JQuery)
Test field-injected class in Spring boot test without using Spring container
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
How to control transactions in Spring Boot without using @Transactional
Output request and response log in Spring Boot
Create a portfolio app using Java and Spring Boot
Testing JPA entities and repositories using Spring Boot @DataJpaTest
Try using DI container with Laravel and Spring Boot
CSRF countermeasure policy and implementation example in REST application using "Spring Boot" + "EXT JS"
Deploy Spring Boot applications to Heroku without using the Heroku CLI
How to call and use API in Java (Spring Boot)
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
8 things to insert into DB using Spring Boot and JPA
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Try using Spring Boot Security
Easily develop web applications with STS and Spring Boot. In 10 minutes.
Fitted in Spring Boot using a bean definition file named application.xml
Compare Hello, world! In Spring Boot with Java, Kotlin and Groovy
Image Spring Boot app using jib-maven-plugin and start it with Docker
Unknown error in line 1 of pom.xml when using Spring Boot in Eclipse
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
Enable jQuery and Bootstrap in Rails 6 (Rails 6)
Spring Boot Tutorial Using Spring Security Authentication
Write test code in Spring Boot
Implement REST API in Spring Boot
Spring profile function, and Spring Boot application.properties
What is @Autowired in Spring boot?
Implement Spring Boot application in Gradle
Thymeleaf usage notes in Spring Boot
Create a Spring Boot project in intellij and exit immediately after launching
[Spring MVC] Implement dynamic parameters included in URL without using Optional (~ Java7)
[Spring Boot] Post files and other data at the same time [Axios]
Automatically deploy a web application developed in Java using Jenkins [Spring Boot application]