ssm+ajax+mysql带图片表单上传(路径上传)

Posted 码达

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssm+ajax+mysql带图片表单上传(路径上传)相关的知识,希望对你有一定的参考价值。

废话不多直接上代码

  • html页面以及js
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="${ctx}">
<!-- 下拉框 -->
<%@ include file="../top.jsp"%>
<style type="text/css">
   code {
      background-color: #f5f5f5;
   }
   .profile-info-name,.profile-info-value{
       height: 44px
   }
   .profile-info-value{
           padding-top: 6px
   }
   .profile-info-name{
           width:100px;
   }
</style>
</head>

<body class="no-skin" style="margin: 0;padding: 0">
<div id="main" class="main-container ace-save-state" >

    <div class="row" style="padding-top: 10px">
        <div class="col-xs-12">
            <form class="form-horizontal" role="form" method="post" id="addPersionForm" enctype="multipart/form-data">
                <div class="profile-user-info profile-user-info-striped" style="border-bottom: 0px">
                    <div style="width:500px"> 
                        <div class="profile-info-row" >
                            <div class="profile-info-name"> 姓名 </div>
                            <div class="profile-info-value" style="width:388px">
                                <input type="text" placeholder="汉字" name="persion_name" style="width: 210px" />
                            </div>
                        </div>
    
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 性别 </div>
    
                            <div class="profile-info-value">
                                <div class="radio">
                                    <label>
                                        <input name="persion_sex" checked="checked" type="radio" class="ace" value="男"/>
                                        <span class="lbl"></span>
                                    </label>
                                
                                    <label style="margin-left: 20px">
                                        <input name="persion_sex" type="radio" class="ace" value="女"/>
                                        <span class="lbl"></span>
                                    </label>
                                </div>
                            </div>
                        </div>
    
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 身份证号 </div>
    
                            <div class="profile-info-value">
                                <input type="text" placeholder="不少于13位" style="width: 210px" name="persion_id_card"/>
                            </div>
                        </div>
                        
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 手机号 </div>
                            <div class="profile-info-value">
                                <input type="text" placeholder="11位手机号" style="width: 210px" name="persion_phone"/>
                            </div>
                        </div>

                        
        <div class="fitem">  
            <label>头像:</label>  
            <input id="codeUrl" name="codeUrl" accept="image/*" onchange="onupload(this)" type="file" style="width:200px" />  
            <div id="xmTanDiv" style="text-align:center;">  
                <img id="Img" width="180px" height="180px"/>  
            </div>  
        </div>  

                    </div>
                </div>
                    
                <div class="profile-user-info profile-user-info-striped" style="margin-top: 1px">

                    <div class="profile-info-row">
                        <div class="profile-info-name"> 部门名称 </div>

                        <div class="profile-info-value">
                            <input type="text" placeholder="部门名称" style="width: 210px" name="persion_dname" />
                        </div>
                    </div>

                    <div class="profile-info-row">
                        <div class="profile-info-name"> 家庭住址 </div>

                        <div class="profile-info-value">
                            <input type="text" placeholder="家庭住址" style="width: 210px" name="persion_address" />
                        </div>
                    </div>

                    <div class="profile-info-row">
                        <div class="profile-info-name"> 单位代码 </div>

                        <div class="profile-info-value">
                            <select class="chosen-select" data-placeholder="Choose a Country..." style="width: 210px" name="unit_code">
                                <option selected="selected" value="-1">----请选择单位----</option>
                                <c:forEach items="${ulist}" var="u" varStatus="vs" >
                                    <option value="${u.unit_code}">${u.unit_name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                </div>
                </form>
            </div>
        </div>
    </div>
    
    
    <div class="footer">
        <div class="footer-inner">
            <div class="footer-content" style="text-align: right;">
                <button type="button" class="btn btn-danger" onclick="add();" style="margin-right: 15px">确定</button>
                <button type="button" onclick="top.Dialog.close();" style="margin-right: 2px" class="btn" >取消</button>
            </div>
        </div>
    </div>
    
    

<script type="text/javascript" src="static/js/jquery-1.7.2.js"></script>

</body>
     <script type="text/javascript">
         var editor;
        $(function() {
            var width = $(window).width();
            var height = $(window).height();
            $("#main").css("width",width-2);
            $("#main").css("height",height-75);
        });
        function add(){
            var formdata = new FormData($("#addPersionForm")[0]);
            $.ajax({
                url:"<%=request.getContextPath()%>/persion/addPersion.do",
                type:"POST",
                async: false,
                contentType: false,  
                processData: false,
                cache: false,
                data:formdata,
                dataType:"text",
                success:function(){
                    //关闭弹出框
                    top.Dialog.close();
                    //刷新数据表格
                    $("#main-container").datagrid("reload");
                },
                error:function(){
                    top.Dialog.close();
                    alert("新增失败");
                },
            })
        } 
 
//选择图片,马上预览  
 var image = ‘‘;  
 function onupload(file) {  
     if(!file.files || !file.files[0]){  
     return;  
     }  
     var reader = new FileReader();  
     //读取文件过程方法  
     reader.onload = function (e) {  
         document.getElementById(Img).src = e.target.result;  
         image = e.target.result;  
     }  
     reader.readAsDataURL(file.files[0])  
 }  
        </script>
</html>
  • controller
   /**
     * 
        * @Title: addPersion  
        * @Description: TODO(新增方法)  
        * @param @param upersion
        * @param @param request
        * @param @param response    参数  
        * @return void    返回类型  
        * @throws
     */
        @RequestMapping(value = "/addPersion")
        public void addPersion(HttpServletRequest request){
            try {
                UPersion upersion = new UPersion();
                //解析请求中的数据  
               MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
               
               String persion_name = mpRequest.getParameter("persion_name");
               String persion_sex = mpRequest.getParameter("persion_sex");
               String persion_id_card = mpRequest.getParameter("persion_id_card");
               String persion_phone = mpRequest.getParameter("persion_phone");
               String persion_dname = mpRequest.getParameter("persion_dname");
               String persion_address = mpRequest.getParameter("persion_address");
               String unit_code = mpRequest.getParameter("unit_code");
               
               //解析图片相对路径
               MultipartFile file = mpRequest.getFile("codeUrl");
               //图片存放在项目的位置
               String path = request.getSession().getServletContext().getRealPath("static\\images");
               System.out.println(path);
               String imageUrl = UploadUtil.uploadFile(file, path);  
               
               upersion.setPersion_name(persion_name);
               upersion.setPersion_sex(persion_sex);
               upersion.setPersion_id_card(persion_id_card);
               upersion.setPersion_phone(persion_phone);
               upersion.setPersion_dname(persion_dname);
               upersion.setPersion_address(persion_address);
               upersion.setUnit_code(unit_code);
               upersion.setPersion_image(path+"\\"+imageUrl);
               System.out.println(path+imageUrl);
               persionService.addPersion(upersion);
               
               System.out.println("新增成功");
                
            } catch (Exception e) {
              e.printStackTrace();
            }
            
        }
  • mapper
     <insert id="addPersion" parameterType="com.zkzj.video_ms.model.UPersion">
          insert into u_persion (persion_name, persion_sex, 
          persion_id_card, unit_code, persion_dname, persion_address, 
          persion_phone,persion_photo,persion_image) 
          values (#{persion_name}, #{persion_sex}, 
          #{persion_id_card}, #{unit_code}, #{persion_dname}, #{persion_address}, #{persion_phone}, #{persion_photo}, #{persion_image}) 
     </insert>
  • 工具类UploadUtil
package com.zkzj.video_ms.utils;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
    
    public static String uploadFile(MultipartFile file, String path) throws IOException{
        //上传文件的真实名称
        String name = file.getOriginalFilename();
        /*System.out.println(name);*/
        //获取后缀名
        String suffixName = name.substring(name.lastIndexOf("."));
        /*System.out.println(suffixName);*/
        //自定义随机数
        String hash = Integer.toHexString(new Random().nextInt());
        /*System.out.println(hash);*/
        //新文件名字
        String fileName = hash + suffixName;
        /*System.out.println(fileName);*/
        
        File tempFile = new File(path,fileName);
        if(!tempFile.getParentFile().exists()){
            tempFile.getParentFile().mkdir();
        }   
        if(tempFile.exists()){
            tempFile.delete();
        }
        tempFile.createNewFile();
        file.transferTo(tempFile);
        return tempFile.getName();
    }

}

 

以上是关于ssm+ajax+mysql带图片表单上传(路径上传)的主要内容,如果未能解决你的问题,请参考以下文章

图片上传并回显Ajax异步篇

使用 php 和 ajax 调用在表单提交上上传单张图片

ajax上传图片

SSM框架下,使用ajax请求上传文件(docdocxexcel图片等)

Ajax实现图片上传

使用ajax上传表单(带文件)