JQuery loads Image from SpringBoot RestAPI

In the tutorial, JavaSampleApproach will show you how to create a web application JQuery loads Image from SpringBoot RestAPI.

Related posts:
MultipartFile – How to create Spring Ajax MultipartFile application to download/upload files | SpringBoot + JQuery Ajax + Bootstrap.
BootStrap Image with SpringBoot RestAPI

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.8.1.RELEASE
– JQuery
– Bootstrap
– Spring Boot – 1.5.7.RELEASE

II. Goal

We create a SpringBoot project as below:

Jquery Load Image from SpringBoot RestApi - project structure

-> results:

Jquery Load Image from SpringBoot RestApi - image display on view

Jquery Load Image from SpringBoot RestApi - request logs

III. Practice

Step to do:
– Create SpringBoot project
– Create Web Controller
– Create RestAPI
– Create index.html
– Create Jquery load image

1. Create SpringBoot project

Using Spring Tool Suite to create a Spring Starter Project with needed dependencies:



2. Create Web Controller
package com.javasampleapproach.restapiimage.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
public class WebController {
    public String homepage(){
        return "index";

3. Create RestAPI
package com.javasampleapproach.restapiimage.controller;

import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class RestWebController {
    @GetMapping(value = "/api/image")
    public ResponseEntity getImage() throws IOException {

        ClassPathResource imgFile = new ClassPathResource("image/jsa_about_img.jpg");

        return ResponseEntity
                .body(new InputStreamResource(imgFile.getInputStream()));
4. Create index.html


	  JQuery Load Image from SpringBoot RestAPI


JQuery Load Image from SpringBoot RestAPI

5. Create Jquery load image
$( document ).ready(function() {
	var img = $("", {                
        "alt": "test image",
        "style":"width: 60%; height: 60%",
        "src": "/api/image"
    .on('load', function() {
        if (!this.complete || 
        		typeof this.naturalWidth == "undefined" || 
        		this.naturalWidth == 0) {
            alert('broken image!');
        } else {

IV. Sourcecode


By grokonez | November 18, 2017.

Related Posts

Got Something To Say:

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