Angular + Spring Boot file upload example

Introduction

Here we will see how to upload file using Angular and Spring Boot application. The Angular + Spring Boot file upload example will use the Angular example from and we will see here how to write server side code for Spring Boot application.

We will also exclude the default server Tomcat and include the Jetty server for our Spring Boot application here.

You need to look at the UI side code using Angular for file upload here at https://roytuts.com/file-upload-example-using-angular/

Prerequisites

Eclipse, JDK 10, Gradle, Spring Boot 2.1.2

https://roytuts.com/file-upload-example-using-angular/

Example with Source Code

Creating Project

Create Gradle based Spring Boot application in Eclipse and make sure you have the following build script:

buildscript {
	ext {
		springBootVersion = '2.1.2.RELEASE'
	}
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
apply plugin: 'java-library'
apply plugin: 'org.springframework.boot'
repositories {
    mavenLocal()
    mavenCentral()
}
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") {
    	exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
    }
    compile("org.springframework.boot:spring-boot-starter-jetty:${springBootVersion}")
}

In the above build script we have excluded default Tomcat server and included dependency for Jetty server in order to use Jetty server.

We have used Spring Boot version 2.1.2.

Changing Port

Next create application.properties file in the classpath resource directory (src/main/resources) and change the default port(8080) to use 9000:

server.port=9000

Creating REST Controller

Create below Spring REST Controller to upload file into server:

package com.roytuts.rest.controller;
import java.io.InputStream;
import java.util.logging.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class FileController {
	private static final Logger logger = Logger.getLogger(FileController.class.getName());
	@PostMapping("/upload")
	public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file) throws Exception {
		if (file == null) {
			throw new RuntimeException("You must select the a file for uploading");
		}
		InputStream inputStream = file.getInputStream();
		String originalName = file.getOriginalFilename();
		String name = file.getName();
		String contentType = file.getContentType();
		long size = file.getSize();
		logger.info("inputStream: " + inputStream);
		logger.info("originalName: " + originalName);
		logger.info("name: " + name);
		logger.info("contentType: " + contentType);
		logger.info("size: " + size);
		// Do processing with uploaded file data in Service layer
		return new ResponseEntity<String>(originalName, HttpStatus.OK);
	}
}

In the above Spring REST Controller class, we have used @CrossOrigin annotation to allow the POST request from incoming URL, such as, http://localhost:4200, which is an Angular application URL.

We just print or log the uploaded file information into the console in the above example. The real application should store the file somewhere or process the file for business requirement.

Creating Main Class

Create below main class which will deploy the application into Jetty server at port 9000:

package com.roytuts.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.roytuts")
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Testing the Application

While your Angular application is running and Spring Boot application is also deployed into Jetty server and running, then you can try to upload the file and when you click on the upload button, you should see the following output in the console:

2019-01-19 14:12:11.709  INFO 7328 --- [tp2071522666-24] c.j.rest.controller.FileController       : inputStream: java.io.ByteArrayInputStream@780134d8
2019-01-19 14:12:11.714  INFO 7328 --- [tp2071522666-24] c.j.rest.controller.FileController       : originalName: Claim.pdf
2019-01-19 14:12:11.714  INFO 7328 --- [tp2071522666-24] c.j.rest.controller.FileController       : name: file
2019-01-19 14:12:11.715  INFO 7328 --- [tp2071522666-24] c.j.rest.controller.FileController       : contentType: application/pdf
2019-01-19 14:12:11.715  INFO 7328 --- [tp2071522666-24] c.j.rest.controller.FileController       : size: 8535

You can upload any type of file. From the above output it is clear that I uploaded pdf file.

Source Code

source code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *