How To Upload Image And Display It On Spring MVC

Hi..

In this article I’ll give simple example how to upload image and display it on SpringMVC. We need to add some libs to support this feature. There are:

  • Apache common file upload
  • Apache common io

First, you need to add multipartresolver bean to your servlet configuration. As for me, here is what I added to my dispatcher-servlet.xml

<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/font/**" location="/font/" />
	
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

The key to display your uploaded image is put the image to folder that can be called from your view. From my dispatcher-servlet you can see that I will put the image to folder “img” and call it with url “[baseURL]/img/[nameOfImage]”. Here are some screenshot result of my code.

upload1

upload3

Now we ready to create the view and controller. I have one class base controller which have some function that might be used by other controllers. My sample for this article will display the latest uploaded image.

package com.aries.blog.controller;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author ariestania.winda
 */

public class BaseController {
    
    public static final String PARAM_BASE_URL = "baseURL";
    	
	//get base URL
    public String getBaseURL(HttpServletRequest request){
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
    
}


package com.aries.blog.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;

/**
 *
 * @author ariestania.winda
 */

@Controller
public class PhotoController extends BaseController{
    
    public static final String PARAM_LATESTPHOTO = "LATEST_PHOTO_PARAM";
            
    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.GET)
    public String uploadPhotoForm(ModelMap model, HttpServletRequest request){
        model.addAttribute(PARAM_BASE_URL, getBaseURL(request));
        return "uploadPhoto";
    }
    
    @RequestMapping(value = "/uploadimgctlr", method = RequestMethod.POST)
    public String uploadImageCtlr(ModelMap model,
            HttpServletRequest request, 
            @RequestParam MultipartFile file){
        String latestUploadPhoto = "";
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        File dir = new File(rootPath + File.separator + "img");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
        latestUploadPhoto = file.getOriginalFilename();
		
	//write uploaded image to disk
        try {
            try (InputStream is = file.getInputStream(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                int i;
                while ((i = is.read()) != -1) {
                    stream.write(i);
                }
                stream.flush();
            }
        } catch (IOException e) {
            System.out.println("error : " + e.getMessage());
        }
        
	//send baseURL to jsp
        model.addAttribute(PARAM_BASE_URL, getBaseURL(request));
	//send photo name to jsp
        model.addAttribute(PARAM_LATESTPHOTO, latestUploadPhoto);
        return "uploadPhoto";
    }  
}

Then here is my jsp.

<%@page import="com.aries.blog.controller.PhotoController"%>
<%@page import="com.aries.blog.controller.BaseController"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <%
            String baseURL = (String) request.getAttribute(BaseController.PARAM_BASE_URL);
            String latestPhotoUpload = (String) request.getAttribute(PhotoController.PARAM_LATESTPHOTO);
        %>
        <title>Upload Photo</title>
        <!-- BOOTSTRAP STYLES-->
        <link href="<%=baseURL%>/css/bootstrap.min.css" rel="stylesheet" />

    </head>
    <body>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="panel panel-primary" style="margin-bottom: 0px;">
                    <div class="panel-heading">
                        Form Upload Photo
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-6">
                                <form role="form" method="POST" action="<%=baseURL%>/uploadimgctlr" enctype="multipart/form-data">
                                    <div class="form-group">
                                        <label>File input</label>
                                        <input type="file" method="POST" accept=".jpg" name="file"/>
                                    </div>  
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-primary">Upload</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <%if (latestPhotoUpload != null && !"".equals(latestPhotoUpload)) {%>
                        <div class="row">
                            <div class="col-md-12">
                                <img src="<%=baseURL%>/img/<%=latestPhotoUpload%>" class="col-md-12"/>
                            </div>
                        </div>
                        <%}%>

                    </div>
                </div>
            </div>            
        </div>        
    </body>
</html>

Hope this simple example can be help. Happy coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s