WEB应用开发--SpringMVC部分学习(三)--初步实现SpringMVC文件上传功能

功能搭建梳理

1.导入jar包

2.加入文件解析器

3.成功搭建登录成功success界面

4.通过界面的"添加头像"功能跳转添加界面

5添加必要的ajaxfileupload.js组件

6.实现上传功能并将本地图库部署到Tomcat服务器中

7.获取图片通过数据库绑定用户头像添加至success界面

导入上传下载所需 jar 文件

  <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

加入文件解析器加入spring_mvc.xml中

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"></property><!--上传后编码-->
    <property name="maxUploadSize" value="104857600"></property><!--上传大小限制-->
</bean>

搭建success界面并添加"头像添加界面"的跳转

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>信息管理系统界面</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
        $(function(){
            var account=window.sessionStorage.getItem("account");
            var newFileName=window.sessionStorage.getItem("newFileName");
            console.log(newFileName+"  111");
           if(account==null){
               location.replace("login.html");
               return;
           }
            $("#accountId").html(account)

        })
//安全退出功能实现
        function exit(){
            if(confirm("您确定要退出吗?")){
                window.sessionStorage.removeItem("account");
                $.get("login/loginOut",function (res) {
                    location.replace("login.html");
                })
            }}
    </script>
</head>
<body>
<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="系统首页" />
            </div>
            <div class="topright">
                <ul>
                    <li><span><img src="images/help.png" title="帮助"  class="helpimg"/></span><a href="#">帮助</a></li>
                    <li><a href="#">关于</a></li>
                    <li><a href="#" target="_parent" onclick="exit()">退出</a></li>
                    <li id="imgId"><a href="upload.html" target="rightFrame">上传头像</a></li>
                </ul>
                <div class="user">
                    <span id="accountId"></span>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td width="187" valign="top"  height="100%"  style="background:#f0f9fd;">
            <div class="lefttop"><span></span>操作菜单</div>
            <dl class="leftmenu">
                <dd>
                    <div class="title">
                        <span><img src="images/leftico01.png" /></span>
                        <a href="">管理信息</a>
                    </div>
                </dd>
            </dl>
        </td>
        <td>
            <iframe name="rightFrame" src="list.html" width="100%" height="600"></iframe>
        </td>
    </tr>
</table>
</body>
</html>

在这里插入图片描述

注意:在此时的upload.html(添加头像)界面我们如果想实现添加文件的功能,必须添加相关的ajaxfileupload.js组件来实现该功能

ajaxfileupload.js组件的添加

ajaxfileupload.js组件源码如下,读者可以自行导入自己的文件夹中,注意地址标清

在这里插入图片描述

jQuery.extend({
    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';

        document.body.appendChild(io);

        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);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');
        return form;
    },
//就是这个函数。
    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();
            cloneElement.attr({'name':name,'value':value});
            $(cloneElement).appendTo(form);
        }
        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);
            try
            {
                if(io.contentWindow)
                {
                    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;
                }
            }catch(e)
            {
                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);

                jQuery(io).unbind()

                setTimeout(function()
                {	try
                {
                    $(io).remove();
                    $(form).remove();

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

                }, 100)

                xml = null

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

        } catch(e)
        {
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            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" )
            jQuery("<div>").html(data).evalScripts();
        //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})

upload.html的简易构建

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <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(){
            $.ajaxFileUpload({
                    url: 'admin/fileUpload', //用于文件上传的服务器端请求地址 调动后端接口
                    fileElementId: 'fileID', //文件上传域的ID
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data){
                        if(data.code==200){
                        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'/>";
                        window.sessionStorage.setItem("newFileName",imgsrc);
                    }
                }}
            )
        }
    </script>
</head>
<body>
上传头像
<input type="file" name="fileName" accept=".jpg,.png,.gif" id="fileID">//限制添加文件的格式
<input type="button" value="上传头像" onclick="fileUpload()">
</body>
</html>

在这里插入图片描述

通过服务器地址访问,我们进行编写Service层代码,在此期间我们还有一个问题还就是如何避免上传的图片重名?

我们可以通过编写一个util组件根据时间生成随机数用于给图片重命名

防止重名添加Util组件代码

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();//字母与数字组合的随机数
        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;

@Controller
@RequestMapping(path = "/admin")
public class AdminController {
    @Autowired
    AdminService adminService;
    /*apache文件+springmvc组件*/
   @ResponseBody
   @PostMapping(path = "/fileUpload")
   public CommonResult fileUpload(@RequestParam("fileName") CommonsMultipartFile file, HttpSession session){
       CommonResult commonResult=null;

       System.out.println(file.getOriginalFilename());
       Admin admin=(Admin)session.getAttribute("admin");
       File f0=new File("D:\\userimg\\admin\\"+admin.getAccount());
       if (!f0.exists()){
           f0.mkdir();
       }
       String oldFileName=file.getOriginalFilename();
       String newFileName= Stringutil.newFileName(oldFileName);//避免文件重名,生成新文件名
       File f=new File(f0,newFileName);
       try {
           file.transferTo(f);
           //保存用户与文件的关系,把文件地址响应给前端
           Admin a=new Admin();
           a.setId(admin.getId());
           a.setNewFileName(newFileName);
           a.setOldFileName(oldFileName);
           adminService.updateAdmin(a);

           commonResult=new CommonResult(200,"上传成功",a);
           // 存储文件可能会重名,借助数据库储存文件与账号的关系
       } catch (IOException e) {
           e.printStackTrace();
           commonResult=new CommonResult(200,"上传失败",null);
       }
       return commonResult;
   }
}

将图库部署至服务器上

在这里我们已经可以通过文件上传的地址调动后端接口了,我们还需要将上传的图片文件部署到服务器中

在这里插入图片描述

这样打开运行我们就可以将图片上传到本地图库,再上传到服务器中

将头像添加至success界面

最后一步获取图片通过数据库绑定用户头像添加至success界面

再success.html加入以下代码即可

//判断用户是否有头像
           if (newFileName != "null"){
               var imgsrc="http://localhost:8080/userimg/admin/"+account+"/"+newFileName;
               console.log(imgsrc);
               document.getElementById("imgId").innerHTML="<img src='"+imgsrc+"' width='50' height='50'/>";
           }

开始验证

上传图片,点击上传

在这里插入图片描述
上传成功实时更新

再次重新登录

在这里插入图片描述

依旧存在

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值