SSM实现图片上传附带form表单数据并显示在页面(IDEA版)

最近在做一个项目时,遇到一个之前没接触过的问题,那就是如标题所述,关于图片文件上传已经附带form表单数据至数据库中,并可以在页面进行访问。

首先要搭建好ssm框架,这个我就不在详细描述了。
其次是,要想访问静态资源文件,必须设置虚拟路径,否则会访问不到,虚拟路径的设置有几种方法,我用的是设置tomcat的虚拟路径,在tomcat/config/路径下找到server.xml文件,
1、在Host标签下添加

 <Context path="/upload" docBase="E:\upload" reloadable="true" ></Context>

2、在IDEA中设置,如下图:
SSM实现图片上传附带form表单数据并显示在页面(IDEA版)_第1张图片
准备工作做好后,就开始编程了
1、创建实体类(Equipment.java)ps:因为我的项目是健身房管理系统,所以直接用器材实体类了:

package com.qinhua.gyg.bean;

import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

public class Equipment {
    private Integer equipmentId;

    private String equipmentName;

    private String equipmentImage;

    private String equipmentPrice;

    private Date equipmentBuyTime;


    public Integer getEquipmentId() {
        return equipmentId;
    }

    public void setEquipmentId(Integer equipmentId) {
        this.equipmentId = equipmentId;
    }

    public String getEquipmentName() {
        return equipmentName;
    }

    public void setEquipmentName(String equipmentName) {
        this.equipmentName = equipmentName == null ? null : equipmentName.trim();
    }

    public String getEquipmentImage() {
        return equipmentImage;
    }

    public void setEquipmentImage(String equipmentImage) {
        this.equipmentImage = equipmentImage;
    }

    public String getEquipmentPrice() {
        return equipmentPrice;
    }

    public void setEquipmentPrice(String equipmentPrice) {
        this.equipmentPrice = equipmentPrice;
    }

    public Date getEquipmentBuyTime() {
        return equipmentBuyTime;
    }

    public void setEquipmentBuyTime(Date equipmentBuyTime) {
        this.equipmentBuyTime = equipmentBuyTime;
    }

}

2、在dao层创建EquipmentMapper.java

public interface EquipmentMapper{
	List<Equipment> selectByExample();

    int saveEquipment(Equipment equipment);
}

3、在resources目录下创建一个mapper文件夹,用来存放dao层各个mapper的映射文件。创建EquipmentMapper.xml

<select id="selectByExample" parameterType="com.qinhua.gyg.bean.EquipmentExample" resultMap="BaseResultMap">
    select * from tbl_equipment
  </select>

<insert id="saveEquipment" parameterType="com.qinhua.gyg.bean.Equipment">
    insert into tbl_equipment(equipment_id,equipment_name,equipment_price,equipment_buy_time,equipment_image)
    values (#{equipmentId},#{equipmentName},#{equipment_price},#{equipmentBuyTime},#{equipmentImage})
</insert>

4、然后是创建controller类EquipmentController.jave

@Autowired
    private EquipmentService equipmentService;

    @RequestMapping("/equipments")
    public String getEquipmentsWithJson(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
//        引入pageHelper分页插件
//        调用方法,传入页面,以及size
        PageHelper.startPage(pn,5);
//        startPage后面紧跟的这个查询就是一个分页查询
        List<Equipment> equipmentList =equipmentService.getAll();
//        使用pageInfo包装查询的结果,将page交给页面(封装了详细的分页信息,包括查询的结果),并传入连续显示的页数
        PageInfo page = new PageInfo(equipmentList,5);
        model.addAttribute("pageInfo",page);
        return "equipmentList";
    }
@RequestMapping("/addEquipment")
    @ResponseBody
    public Msg addEquipment(@RequestParam(value = "equipmentImage",required = false)MultipartFile file,
                            String equipmentName,
                            String equipmentPrice,
                            String equipmentBuyTime,
                            HttpServletRequest request) throws ParseException {

        Equipment equipment = new Equipment();
        String filePath = "E:\\upload"; //定义图片上传后的路径
        String alies = "upload";//tomcat设置的别名
        String newFileName = "/" + alies + "/" + fileOperate(file,filePath);
//     将字符串转为时间格式
        //注意:SimpleDateFormat构造函数的样式与strDate的样式必须相符
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(equipmentBuyTime);
        //对数据库进行操作
        equipment.setEquipmentName(equipmentName);
        equipment.setEquipmentImage(newFileName);
        equipment.setEquipmentPrice(equipmentPrice);
        equipment.setEquipmentBuyTime(date);
        equipmentService.saveEquipment(equipment);  
        return Msg.success();
    }
    /**
     * 封装操作文件方法, 添加用户 和修改用户都会用到
     * @param file
     * @param filePath
     * @return
     */
    private String fileOperate(MultipartFile file,String filePath) {
        String originalFileName = file.getOriginalFilename();//获取原始图片的扩展名
        System.out.println("图片原始名称:"+originalFileName);
        String newFileName = UUID.randomUUID()+originalFileName;  //新的文件名称
        System.out.println("新的文件名称:"+newFileName);
        File targetFile = new File(filePath,newFileName); //创建新文件
        try {
            file.transferTo(targetFile); //把本地文件上传到文件位置 , transferTo()是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFileName;
    }

5、我把提交用bootstrap的模态框附在显示界面中


```java
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());

    %>
    <!-- web路径:
    不以/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出问题。
    以/开始的相对路径,找资源,以服务器的路径为标准(http://localhost:3306);需要加上项目名
            http://localhost:3306/crud
     -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<script type="text/javascript">


    //选择图片,马上预览
    var image = '';
    function upload(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])
    }
    function addEquipment() {
        $("#equipment_add_model").modal({
            backdrop:"static"
        });
    }


    function modalAddEquipment() {

        var formdata = new FormData($("#equipment_form")[0]);
        $.ajax({
            async: false,
            cache:false,
            url:'addEquipment',
            data:formdata,
            type:'POST',
            contentType: false,
            processData: false,
            success:function (result) {
                if(result.code == 100){
                    alert("成功")
                }else {
                    alert("失败")
                }
            }
        });

    }
</script>
<!-- Modal 新增器材模态框-->
<div class="modal fade" id="equipment_add_model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">器材添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="equipment_form" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">器材名称</label>
                        <div class="col-sm-10">
                            <input type="text" name="equipmentName" class="form-control"  placeholder="equipmentName">
                        </div>
                    </div>

                    <div class="form-group">
                        <label  class="col-sm-2 control-label">器材图片</label>
                        <div class="col-sm-10">
                            <input type="file" id="equipmentImage" name="equipmentImage" accept="image/*"
                                   onchange="upload(this)" >
                            <div>
                                <img id="Img" width="180px" height="180px"/>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label  class="col-sm-2 control-label">器材价格</label>
                        <div class="col-sm-10">
                            <input type="text" name="equipmentPrice" class="form-control"  placeholder="equipmentPrice">
                        </div>
                    </div>

                    <div class="form-group">
                        <label  class="col-sm-2 control-label">购买时间</label>
                        <div class="col-sm-10">
                            <input type="date" name="equipmentBuyTime" class="form-control"  >
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="modalAddEquipment()">添加</button>
            </div>
        </div>
    </div>
</div>
<%--  搭建显示页面  --%>
<div class="container">
    <%--        标题行--%>
    <div class="row">
        <div style="float:left; display:inline">
            <h2>器材管理>>></h2>
        </div>
        <div >
            <h3 style="float:left; display:inline">器材列表</h3>
        </div>
    </div>
    <%--        按钮行--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary" id="add_model" onclick="addEquipment()" >新增</button>
            <button class="btn btn-danger">删除</button>
        </div>
    </div>
    <%--        信息行--%>
    <div class="row"></div>
    <div class="col-md-12">
        <table class="table table-hover">
            <tr>
                <th>#</th>
                <th>名称</th>
                <th>图片</th>
                <th>价格</th>
                <th>购买时间</th>
                <th>操作</th>
            </tr>
            <c:forEach items="${pageInfo.list}" var="equipment">
                <tr>
                    <th>${equipment.equipmentId}</th>
                    <th>${equipment.equipmentName}</th>
                    <th>
                        <c:if test="${equipment.equipmentImage !=null }">

                        <img id="images" alt="" src="${equipment.equipmentImage }" style="width: 100px;height: 100px">
                        </c:if>
                    </th>

                    <th>${equipment.equipmentPrice}</th>
                    <th>
                        <fmt:formatDate value="${equipment.equipmentBuyTime}" pattern="yyyy-MM-dd"></fmt:formatDate>
                    </th>
                    <th>
                        <button class="btn btn-primary btn-sm">
                            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>编辑
                        </button>
                        <button class="btn-danger btn-sm">
                            <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除
                        </button>
                    </th>
                </tr>
            </c:forEach>

        </table>
    </div>
    <%--        分页行--%>
    <div class="row">
        <%--            分页文字信息--%>
        <div class="col-md-6">
            当前第${pageInfo.pageNum},总共${pageInfo.pages}页,总共有${pageInfo.total}条记录
        </div>
        <%--                分页条信息--%>
        <div class="col-md-6">
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li><a href="${APP_PATH}/equipments?pn=1">首页</a></li>
                    <c:if test="${pageInfo.hasPreviousPage}">
                        <li>
                            <a href="${APP_PATH}/equipments?pn=${pageInfo.pageNum-1}" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                    </c:if>

                    <c:forEach items="${pageInfo.navigatepageNums}" var="page_num">
                        <%--                            判断是否当前页码,是则当前页码数高亮显示--%>
                        <c:if test="${page_num == pageInfo.pageNum}">
                            <li class="active"><a href="#">${page_num}</a></li>
                        </c:if>
                        <%--                            判断是否当前页码,不是则不高亮显示--%>
                        <c:if test="${page_num != pageInfo.pageNum}">
                            <%--                                给每个页码按钮添加页面请求--%>
                            <li><a href="${APP_PATH}/equipments?pn=${page_num}">${page_num}</a></li>
                        </c:if>
                    </c:forEach>
                    <c:if test="${pageInfo.hasNextPage}">
                        <li>
                            <a href="${APP_PATH}/equipments?pn=${pageInfo.pageNum+1}" " aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </c:if>
                    <li><a href="${APP_PATH}/equipments?pn=${pageInfo.pages}" >末页</a></li>
                </ul>
            </nav>
        </div>
    </div>
</div>


</body>
</html>



以下是运行截图:
SSM实现图片上传附带form表单数据并显示在页面(IDEA版)_第2张图片
SSM实现图片上传附带form表单数据并显示在页面(IDEA版)_第3张图片
SSM实现图片上传附带form表单数据并显示在页面(IDEA版)_第4张图片
SSM实现图片上传附带form表单数据并显示在页面(IDEA版)_第5张图片
我也是个新手,望各位大佬批评指点!!
如有问题可以联系QQ:2682882952

你可能感兴趣的:(SSM实现图片上传附带form表单数据并显示在页面(IDEA版))