Angular Spring Boot Upload Image (2024)
In this tutorial, we'll show you how to upload image using Angular 8 + Spring Boot with following rest endpoints.
POST
method to Upload image usingMultipartFile[] file
as a parameter.GET/image/info
method with image name, provide image information containing name of the image, type and image in byte format.
Angular 8 Upload Image Implementation
Create Angular 8 Upload Image Project
Project Structure
Angular Root Module
The root module of the app is defined by app.module.ts
. It specifies the external modules that will
be used in the application and specifies the components that belong to this module, such as the
HttpClientModule
and FormsModule
.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
AppComponent is the base component of the application. It will be the host of the new component to upload the image.
This component calls the below rest api's to upload the image and to view the image.
POST
method to Upload image usingMultipartFile[] file
as a parameter.GET/image/info
method with image name, provide image information containing name of the image, type and image in byte format.
import { HttpClient, HttpEventType } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private httpClient: HttpClient) { }
uploadedImage: File;
dbImage: any;
postResponse: any;
successResponse: string;
image: any;
public onImageUpload(event) {
this.uploadedImage = event.target.files[0];
}
imageUploadAction() {
const imageFormData = new FormData();
imageFormData.append('image', this.uploadedImage, this.uploadedImage.name);
this.httpClient.post('http://localhost:8080/upload/image/', imageFormData, { observe: 'response' })
.subscribe((response) => {
if (response.status === 200) {
this.postResponse = response;
this.successResponse = this.postResponse.body.message;
} else {
this.successResponse = 'Image not uploaded due to some error!';
}
}
);
}
viewImage() {
this.httpClient.get('http://localhost:8080/get/image/info/' + this.image)
.subscribe(
res => {
this.postResponse = res;
this.dbImage = 'data:image/jpeg;base64,' + this.postResponse.image;
}
);
}
}
Checkout our related posts :
Create HTML form to upload image
Create HTML form app.component.html
to upload image:
<div class="container">
<h1>TechGeekNext Upload Image Example</h1>
<br>
<form>
<div class="form-group">
<input type="file" (change)="onImageUpload($event)">
<input type="button" (click)="imageUploadAction()" value="Upload Image" class="btn1">
</div>
<div>
<output *ngIf=successResponse class="success"><b>{{successResponse}}</b></output>
</div>
<br>
<div class="form-group">
<input type="text" id="image" placeholder="Search Image" [(ngModel)]="image" name="image" />
<input type="button" (click)="viewImage()" value="View Image" class="btn1">
</div>
<div *ngIf=dbImage>
<img [src]="dbImage">
</div>
</form>
</div>
Refer Angular Upload Image Example for full implementation with Source Code.
Spring Boot Upload Image Implementation
Create Spring Boot Project from Spring Initializer site https://start.spring.io/
Project Structure
Maven Dependency
All we need is spring-boot-starter-web
for RestController,
mysql-connector-java
for database dependencies in pom.xml, add
org.projectlombok
for auto generating getters/setters/constructor.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-upload-image</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-upload-image</name>
<description>Spring Boot Upload Image</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Database Connection Details
Provide database details in application.properties
.
spring.datasource.url=jdbc:mysql://localhost/imagesdb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
RestController to upload image
Create RestController class and define below rest endpoint:
POST
method to Upload image usingMultipartFile[] file
as a parameter.GET/image/info
method with image name, provide image information.GET/image
method with image name, can view image.
package com.techgeeknext.controller;
import com.techgeeknext.entities.Image;
import com.techgeeknext.repositories.ImageRepository;
import com.techgeeknext.util.ImageUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Optional;
@RestController
//@CrossOrigin(origins = "http://localhost:8082") open for specific port
@CrossOrigin() // open for all ports
public class ImageController {
@Autowired
ImageRepository imageRepository;
@PostMapping("/upload/image")
public ResponseEntity<ImageUploadResponse> uplaodImage(@RequestParam("image") MultipartFile file)
throws IOException {
imageRepository.save(Image.builder()
.name(file.getOriginalFilename())
.type(file.getContentType())
.image(ImageUtility.compressImage(file.getBytes())).build());
return ResponseEntity.status(HttpStatus.OK)
.body(new ImageUploadResponse("Image uploaded successfully: " +
file.getOriginalFilename()));
}
@GetMapping(path = {"/get/image/info/{name}"})
public Image getImageDetails(@PathVariable("name") String name) throws IOException {
final Optional<Image> dbImage = imageRepository.findByName(name);
return Image.builder()
.name(dbImage.get().getName())
.type(dbImage.get().getType())
.image(ImageUtility.decompressImage(dbImage.get().getImage())).build();
}
@GetMapping(path = {"/get/image/{name}"})
public ResponseEntity<byte[]> getImage(@PathVariable("name") String name) throws IOException {
final Optional<Image> dbImage = imageRepository.findByName(name);
return ResponseEntity
.ok()
.contentType(MediaType.valueOf(dbImage.get().getType()))
.body(ImageUtility.decompressImage(dbImage.get().getImage()));
}
}
Refer Spring Boot Upload Image Example for full implementation with Source Code.
Test Angular Spring Boot Image Upload Example
- Prerequisite : Start the Spring Boot Rest Api's application required for angular image upload example.
- Use below command to install all the dependencies required for the project.
npm install
- Run the application by using below command:
ng serve
- By default application will open in browser at http://localhost:4200/ url.
POST - Upload Image
Choose File and click on Upload Image button to upload the image.View Image
Provide the image name in the search input field and click on View Image to view the image.
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot Upload Image Example
- Download it here - Angular Image Upload Example