Rectangle 27 0 Send value and file from view to controller by ajax method?

The attached is a Maven project;
The server side code is implemented as a Spring MVC controller;
The client side code is implemented in the simple "index.jsp" file;
The project uses Java 8 and Tomcat 7. If you want to try this example by yourself, I would recommend JDK 8 and Eclipse Luna Java EE IDE for web developers or above.
I will assume that you have some general background on Maven, Spring MVC, and jQuery. If you are not familiar with these, you can always check out the internet to get the ideas on them.

The server side code
The attached is a Maven project, the POM file is the following:

Hide   Shrink    Copy Code
<project xmlns=""



        <!-- Minimal dependencies for Spring MVC -->



        <!-- Multi-part file support -->

        <!-- Jackson dependencies -->

        <!-- Sevlet jars for compilation, provided by Tomcat -->



The "web.xml" and the "mvc-dispatcher-servlet.xml" file are the following:

Hide   Shrink    Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
    id="WebApp_ID" version="3.0">

    <display-name>D3 Example</display-name>




Hide   Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" 

     <context:component-scan base-package="" />
     <mvc:annotation-driven />

     <bean id="multipartResolver"
        <property name="maxUploadSize" value="1048576"/>
The MVC controller that takes the uploaded file is implemented in the "FileController" file:

Hide   Shrink    Copy Code

import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class FileController {

    @RequestMapping(value = "/echofile", method = RequestMethod.POST, produces = {"application/json"})
    public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
            HttpServletResponse response) throws Exception {

        MultipartFile multipartFile = request.getFile("file");
        Long size = multipartFile.getSize();
        String contentType = multipartFile.getContentType();
        InputStream stream = multipartFile.getInputStream();
        byte[] bytes = IOUtils.toByteArray(stream);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("fileoriginalsize", size);
        map.put("contenttype", contentType);
        map.put("base64", new String(Base64Utils.encode(bytes)));

        return map;
The "echoFile()" method takes the uploaded file though the "MultipartHttpServletRequest" object;
It converts the file content into Base64 format and returns the Base64 content in the JSON response;
The goal of this example is to use jQuery Ajax to upload a file to the server and receive the responded JSON object. Now let us take a look at the client side code.

The client side code
The client side code is implemented in the "index.jsp" file. The HTML part of the file is the following:

Hide   Copy Code
<body style="font-family: calibri; font-size: 8pt">
<form id="fileForm">
    <input type="file" name="file" />
    <button id="btnUpload" type="button">Upload file</button>
    <button id="btnClear" type="button">Clear</button>
<div id="imgContainer"></div>
The Javascript part of the file is the following:

Hide   Shrink    Copy Code
<script type="text/javascript">

var isJpg = function(name) {
    return name.match(/jpg$/i)

var isPng = function(name) {
    return name.match(/png$/i)

$(document).ready(function() {
    var file = $('[name="file"]');
    var imgContainer = $('#imgContainer');

    $('#btnUpload').on('click', function() {
        var filename = $.trim(file.val());

        if (!(isJpg(filename) || isPng(filename))) {
            alert('Please browse a JPG/PNG file to upload ...');

            url: '<%=baseUrl%>api/echofile',
            type: "POST",
            data: new FormData(document.getElementById("fileForm")),
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false
          }).done(function(data) {
              var img = '<img src="data:' + data.contenttype + ';base64,'
                  + data.base64 + '"/>';

          }).fail(function(jqXHR, textStatus) {
              alert('File upload failed ...');


    $('#btnClear').on('click', function() {

The jQuery reference is to the jQuery CDN "<script src="//"></script>". If you want to run this example on your own computer, you need to make sure that you have the internet access, so your browser can download jQuery from the CDN.

The HTML part declared a file input in an HTML form;
In the click event of the "btnUpload" button, an Ajax call is issued to upload the file. The data to be uploaded is a "FormData" object;
Upon a success Ajax call, a JSON response is received. The JSON object should have the Base64 content responded from the server.
In order to show the responded data, I insisted that only JPG/PNG images can be uploaded. The responded Base64 image will be displayed on the web page.