WEB application development -- Part learning of spring MVC -- preliminary realization of spring MVC file upload function

Posted by saeed_violinist on Mon, 28 Feb 2022 12:10:25 +0100

Function construction and sorting

1. Import jar package

2. Add file parser

3. Successfully set up the login success interface

4. Jump to the add interface through the "add Avatar" function of the interface

5 add the necessary Ajax file upload JS component

6. Realize the upload function and deploy the local gallery to the Tomcat server

7. Get the picture, bind the user's Avatar through the database and add it to the success interface

Import, upload and download required jar files


Add file parser and spring_ mvc. In XML

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"></property><!--Post upload code-->
    <property name="maxUploadSize" value="104857600"></property><!--Upload size limit-->

Set up the success interface and add the jump of "Avatar adding interface"

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Information management system interface</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
            margin: 0px;
            padding: 0px;
    <script src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
            var account=window.sessionStorage.getItem("account");
            var newFileName=window.sessionStorage.getItem("newFileName");
            console.log(newFileName+"  111");

//Implementation of safe exit function
        function exit(){
            if(confirm("Are you sure you want to exit?")){
                $.get("login/loginOut",function (res) {
<table border="1" cellspacing="0" cellpadding="0" width="100%" height="100%">
    <tr style="background:url(images/topbg.gif) repeat-x;">
        <td colspan="2">
            <div class="topleft">
                <img src="images/logo.png" title="System home page" />
            <div class="topright">
                    <li><span><img src="images/help.png" title="help"  class="helpimg"/></span><a href="#"> help</a></li>
                    <li><a href="#"> about</a></li>
                    <li><a href="#" target="_ Parent "onclick =" exit() "> Exit</a></li>
                    <li id="imgId"><a href="upload.html" target="rightFrame">Upload Avatar</a></li>
                <div class="user">
                    <span id="accountId"></span>
        <td width="187" valign="top"  height="100%"  style="background:#f0f9fd;">
            <div class="lefttop"><span></span>Operation menu</div>
            <dl class="leftmenu">
                    <div class="title">
                        <span><img src="images/leftico01.png" /></span>
                        <a href="">management information </a>
            <iframe name="rightFrame" src="list.html" width="100%" height="600"></iframe>

Note: in this case, upload HTML (add avatar) interface if we want to realize the function of adding files, we must add relevant Ajax fileUpload JS component to realize this function

ajaxfileupload. Add JS component

ajaxfileupload. The source code of JS component is as follows. Readers can import it into their own folder and pay attention to the address label

    createUploadIframe: function(id, uri)
        //create frame
        var frameId = 'jUploadFrame' + id;

        if(window.ActiveXObject) {
            var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if(typeof uri== 'boolean'){
                io.src = 'javascript:false';
            else if(typeof uri== 'string'){
                io.src = uri;
        else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';


        return io
    createUploadForm: function(id, fileElementId)
        //create form
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        return form;
//That's the function.
    handleError: function( s, xhr, status, e )      {
        // If a local callback was specified, fire it
        if ( s.error ) {
            s.error.call( s.context || s, xhr, status, e );
        // Fire the global callback
        if ( s.global ) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
    addOtherRequestsToForm: function(form,data)
        // add extra parameter
        var originalElement = $('<input type="hidden" name="" value="">');
        for (var key in data) {
            name = key;
            value = data[key];
            var cloneElement = originalElement.clone();
        return form;

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
        var form = jQuery.createUploadForm(id, s.fileElementId);
        if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
            jQuery.event.trigger( "ajaxStart" );
        var requestDone = false;
        // Create the request object
        var xml = {}
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
            var io = document.getElementById(frameId);
                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

                }else if(io.contentDocument)
                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                jQuery.handleError(s, xml, null, e);
            if ( xml || isTimeout == "timeout")
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );

                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
                    status = "error";
                    jQuery.handleError(s, xml, status, e);

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);


                {	try

                } catch(e)
                    jQuery.handleError(s, xml, null, e);

                }, 100)

                xml = null

        // Timeout checker
        if ( s.timeout > 0 )
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
            // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
                form.encoding = 'multipart/form-data';
                form.enctype = 'multipart/form-data';

        } catch(e)
            jQuery.handleError(s, xml, null, e);
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        return {abort: function () {}};


    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            // If you add mimetype in your response,
            // you have to delete the '<pre></pre>' tag.
            // The pre tag in Chrome has attribute, so have to use regex to remove
            var data = r.responseText;
            var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
            var am = rx.exec(data);
            //this is the desired data extracted
            var data = (am) ? am[1] : "";    //the only submatch or empty
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
        //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;

upload. Simple construction of HTML

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <script type="application/javascript" src="js/jquery-1.8.3.min.js"></script>
    <script type="application/javascript" src="js/ajaxfileupload.js"></script>
    <script type="application/javascript">
        function fileUpload(){
                    url: 'admin/fileUpload', //Server side request address transfer back-end interface for file upload
                    fileElementId: 'fileID', //ID of file upload domain
                    dataType: 'json', //The return value type is generally set to json
                    success: function (data){
                        var account=window.sessionStorage.getItem("account");
                        var imgsrc="http://localhost:8080/userimg/admin/"+account+"/"+data.data().newFileName;
                        window.parent.document.getElementById("imgId").innerHTML="<img src='"+imgsrc+"' width='50' height='50'/>";
Upload Avatar
<input type="file" name="fileName" accept=".jpg,.png,.gif" id="fileID">//Limit the format of added files
<input type="button" value="Upload Avatar" onclick="fileUpload()">

Through the server address access, we write the Service layer code. During this period, we have another problem, that is, how to avoid duplicate names of uploaded pictures?

We can write a util component to generate random numbers according to time for renaming images

Prevent duplicate names from adding Util component code

package com.qn.ssm.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

public class Stringutil {
    public static String subFileType(String fileName){
        if (fileName!=null){
            return fileName.substring(fileName.lastIndexOf(".")+1);
        return null;
    public static  String newFileName(String oldFileName){
       // UUID uuid=UUID.randomUUID();// A random number consisting of letters and numbers
        Date date=new Date();
        SimpleDateFormat sdf=new  SimpleDateFormat ("yyyyMMddHHmmssSSS");
        return sdf.format(date)+"."+subFileType(oldFileName);
package com.qn.ssm.controller;
import com.qn.ssm.common.CommonResult;
import com.qn.ssm.model.Admin;
import com.qn.ssm.service.AdminService;
import com.qn.ssm.util.Stringutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@RequestMapping(path = "/admin")
public class AdminController {
    AdminService adminService;
    /*apache File + spring MVC component*/
   @PostMapping(path = "/fileUpload")
   public CommonResult fileUpload(@RequestParam("fileName") CommonsMultipartFile file, HttpSession session){
       CommonResult commonResult=null;

       Admin admin=(Admin)session.getAttribute("admin");
       File f0=new File("D:\\userimg\\admin\\"+admin.getAccount());
       if (!f0.exists()){
       String oldFileName=file.getOriginalFilename();
       String newFileName= Stringutil.newFileName(oldFileName);//Avoid duplicate file names and generate new file names
       File f=new File(f0,newFileName);
       try {
           //Save the relationship between the user and the file, and respond the file address to the front end
           Admin a=new Admin();

           commonResult=new CommonResult(200,"Upload successful",a);
           // The stored file may have the same name. The relationship between the file and the account can be stored with the help of the database
       } catch (IOException e) {
           commonResult=new CommonResult(200,"Upload failed",null);
       return commonResult;

Deploy gallery to server

Here, we can transfer the back-end interface through the file upload address. We also need to deploy the uploaded image files to the server

In this way, we can upload the pictures to the local gallery and then to the server

Add avatar to success interface

The last step is to obtain the image and bind the user's Avatar to the success interface through the database

Then success HTML add the following code

//Judge whether the user has a Avatar
           if (newFileName != "null"){
               var imgsrc="http://localhost:8080/userimg/admin/"+account+"/"+newFileName;
               document.getElementById("imgId").innerHTML="<img src='"+imgsrc+"' width='50' height='50'/>";

Start validation

Upload pictures, click upload

Log in again

Upload successful

Topics: Java Front-end Spring Ajax