zoukankan      html  css  js  c++  java
  • Spring+SpringMVC+MyBatis+easyUI整合优化篇(七)图片上传功能

    前言

    前一篇文章《Spring+SpringMVC+MyBatis+easyUI整合优化篇(六)easyUI与富文本编辑器UEditor整合》讲了富文本编辑器UEditor的整合与使用,虽然其中也集成了图片上传功能,但是有时候需求不同,只需要一个图片上传就行了,不需要全部集成UEditor的,因为UEditor功能比较齐全,因此集成的东西较多,源文件文件也就很多多,是一个较大的插件,如果我只需要一个图片上传功能,却集成这么多东西,是没有必要的,因此本篇单独讲一下图片上传功能。
    功能已经部署完毕,点击这里去操作,账密:admin 123456

    我的github地址

    整合步骤

    基于jQuery上传插件Uploadify

    页面代码:

    //form元素中需添加" enctype='multipart/form-data' "
    <form id="fm" method="post" enctype="multipart/form-data">
            <div style="padding-top:50px;  float:left; 95%; padding-left:30px;">
                <div id="i_do_wrap">
                    <div id="pic11" style="display:none;" class="i_do_div rel">
    
                    </div>
                    <div class="i_do_div rel" id="picture"><p class="i_do_tle r_txt abs font14">展示图片</p>
                    </div>
                </div>
            </div>
        </form>
    

    js上传及回调方法:

    //这里只是上传图片的js方法,并将服务端返回的url放入input标签中
    function initUploadify() {
            $("#uploadify2").uploadify({
                'uploader': 'swf/uploadify2.swf', 			//flash文件的相对路径
                'script': '../loadimg/upload.do',  				//后台处理接口的相对路径
                'fileDataName': 'file', 						//设置上传文件名称,默认为Filedata
                'cancelImg': 'images/cancel.png', 			//每一个文件上的关闭按钮图标
                'queueID': 'div_progress', 					//文件队列的ID,该ID与存放文件队列的div的ID一致
                'queueSizeLimit': 1, 							//当允许多文件生成时,设置选择文件的个数,默认值:999
                'fileDesc': '*.jpg;*.gif;*.png;*.ppt;*.pdf;*.jpeg', 	//用来设置选择文件对话框中的提示文本
                'fileExt': '*.jpg;*.gif;*.png;*.ppt;*.pdf;*.jpeg', 		//设置可以选择的文件的类型
                'auto': true, 								//设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传
                'multi': true, 								//设置为true时可以上传多个文件
                'simUploadLimit': 1, 						//允许同时上传的个数 默认值:1
                'sizeLimit': 2048000,						//上传文件的大小限制
                'buttonText': '上传图片',						//浏览按钮的文本,默认值:BROWSE
                'displayData': 'percentage',     			//上传队列显示的数据类型,percentage是百分比,speed是上传速度
                //回调函数
                'onComplete': function (evt, queueID, fileObj, response, data) {
                    $("#img11").attr("src", "../" + response);
                    $("#input11").val(response);
                    $("#pic11").removeAttr("style");
                    $("#img11").removeAttr("style");
                    return false;
                },
                'onError': function (event, queueID, fileObj, errorObj) {
                    if (errorObj.type === "File Size") {
                        alert("文件最大为3M");
                        $("#uploadify").uploadifyClearQueue();
                    }
                },
                'onQueueFull': function (event, queueSizeLimit) {
                    alert("最多上传" + queueSizeLimit + "张图片");
                    return false;
                }
            });
        }
    

    新建upload文件夹

    SpringMVC配置文件

    服务端代码中实现图片上传使用的是MultipartFile类,需要在SpringMVC配置文件中新增配置如下:

        <bean id="multipartResolver"    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="1000000"/>
            <property name="defaultEncoding" value="UTF-8"/>
        </bean>
    

    图片上传处理代码

    @RequestMapping("/upload")
        public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception {
            ServletContext sc = request.getSession().getServletContext();
            String dir = sc.getRealPath("/upload");
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            Random r = new Random();
            String imgName = "";
            if (type.equals("jpg")) {
                imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpg";
            } else if (type.equals("png")) {
                imgName = sdf.format(new Date()) + r.nextInt(100) + ".png";
            } else if (type.equals("jpeg")) {
                imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpeg";
            } else {
                return null;
            }
            FileUtils.writeByteArrayToFile(new File(dir, imgName), file.getBytes());
            //返回图片的url,结合前端js回调实现上传并回显的功能
            response.getWriter().print("upload/" + imgName);
            return null;
        }
    

    SpringMVC图片上传,成功后异步回传url,上传与实体存储步骤分开。

    //保存到数据库中
        function savePicture() {
            $("#fm").form("submit", {
                url: url,
                onSubmit: function () {
                    return $(this).form("validate");
                },
                success: function (result) {
                    var result = eval('(' + result + ')');
                    if (result.success) {
                        $.messager.alert("系统提示", "保存成功");
                        $("#dlg").dialog("close");
                        $("#dg").datagrid("reload");
                        resetValue();
                    } else {
                        $.messager.alert("系统提示", "保存失败");
                        window.location.reload();
                        return;
                    }
                }
            });
        }
    

    数据库文件

    DROP TABLE IF EXISTS `ssm_picture`;
    
    CREATE TABLE `ssm_picture` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `path` varchar(150) DEFAULT NULL,
      `type` int(11) DEFAULT NULL,
      `time` varchar(100) DEFAULT NULL,
      `url` varchar(200) DEFAULT NULL,
      `grade` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    LOCK TABLES `ssm_picture` WRITE;
    
    UNLOCK TABLES;
    
    
    

    结语

    最近两篇文章主要是增加了本项目的一些小功能点,如果有其他建议的话,也希望能留言或者发私信给我,如果感觉还可以的话,也会陆续的添加到项目中来。

  • 相关阅读:
    MT【90】图论基础知识及相关例题
    MT【89】三棱锥的体积公式
    Qt之界面实现技巧
    QCompleter自动补全
    Qt之开机自启动
    Qt之日志输出文件
    相遇Qt5
    QT中的pro文件的编写
    qt下的跨目录多工程编译
    用QT打开网页
  • 原文地址:https://www.cnblogs.com/han-1034683568/p/6692150.html
Copyright © 2011-2022 走看看