ssm图片上传

图片上传这个功能搞了好久,终于搞好了

基本思想:

    1.前端页面提交input类型为file的文件

     注意:form表单内必须增加enctype="multipart/form-data"

     //不懂的可以 :https://blog.csdn.net/yiye2017zhangmu/article/details/80820806

    2.业务逻辑层controller中接受前端传来的文件表示为MultipartFile file,通过UUID.randomUUID()对名字进行重建,然后对获取的文件进行路径重组、封装,然后把本地文件上传到封装上传文件位置的全路径,然后将按新名字保存到数据库。

    3.查询表,通过el将信息输出到前端页面

具体代码如下:

  1.service定义接口

  public interface productService {
      void save(Smallmarket product);
      List<Smallmarket> getAllproduct();
 	

  }

 2.实现

 @Service("productService")
        public class productServiceImp implements productService {
   
	@Resource
	private SmallmarketMapper mapper;
	
	@Override
	public void save(Smallmarket product) {
	   mapper.insert(product);
	}}       
	@Override
	public List<Smallmarket> getAllproduct() {
		return mapper.findAll();
	}

 3.dao层接口以及mapper.xml配置

       

public interface SmallmarketMapper {
	
	
	public void insert(Smallmarket product);
	
	List<Smallmarket> findAll();

	}

     

    <insert id="insert" parameterType="model.Smallmarket" >
           insert into smallmarket (id, product_name, product_prise, 
             product_image)
             values (#{id,jdbcType=INTEGER}, #{productName,jdbcType=VARCHAR}, #{productPrise,jdbcType=INTEGER}, 
           #{productImage,jdbcType=VARCHAR})
     </insert>

     <select id="findAll" resultType="model.Smallmarket">
        select id id,product_name productName,product_prise productPrise, product_image productImage from       smallmarket

      </select>


4.controller层

 public class imageController {


	@Autowired
	private productService  productservice;
	


	
	@RequestMapping("/toFate")
	public String toFate(Model model) {
		List<Smallmarket> smallList=productservice.getAllproduct();
		model.addAttribute("smallList", smallList);
		return "/getFate";
	}
	
	@RequestMapping("/toAddProduct")
	public String toAddProduct() {
		return "/addProduct";
	}
	
	 /**
     * 保存商品
     * @param image
     * @param product
     * @param map
     * @return
     * @throws IOException
     */


  @RequestMapping("/uploadPic")
 public String uploadPic(String productName,Integer productPrise,MultipartFile file,Model model)  throws IOException{
	  /**
       * 上传图片
       */
	  //图片上传成功后,将图片的地址写到数据库
      String filePath = "G:\\image";//保存图片的路径
      //获取原始图片的拓展名
      String originalFilename = file.getOriginalFilename();
      //新的文件名字
      String newFileName = UUID.randomUUID()+originalFilename;
      //封装上传文件位置的全路径
	  File targetFile=new File(filePath,newFileName);
	//把本地文件上传到封装上传文件位置的全路径
	  file.transferTo(targetFile);
	  Smallmarket small=new Smallmarket();
	  small.setProductName(productName);
	  small.setProductPrise(productPrise);
	  small.setProductImage(newFileName);
      
	  productservice.save(small);
     
	  return "redirect:/user/toFate"; 
	  
	 }

  }

5.前端俩个页面:

  1.getFate.jsp

        <%@ page language="java" contentType="text/html; charset=UTF-8"

	pageEncoding="UTF-8"%>
          <%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/sliding_effect.js"></script>
<title>小超市</title>
<style type="text/css">
    #images{
        width: 50px;
        height: 50px;
    }
</style>
</head>
<body>
<nav class="navbar navbar-inverse">
		<div class="container-fluid">
			<!-- Brand and toggle get grouped for better mobile display -->
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed"
					data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
					aria-expanded="false">
					<span class="sr-only">Toggle navigation</span> <span
						class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="<%=basePath%>user/getHome">Brand</a>
			</div>


			<!-- Collect the nav links, forms, and other content for toggling -->
			<div class="collapse navbar-collapse"
				id="bs-example-navbar-collapse-1">
				<ul class="nav navbar-nav">
					<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
					<li><a href="#">Link</a></li>
					<li class="dropdown"><a href="#" class="dropdown-toggle"
						data-toggle="dropdown" role="button" aria-haspopup="true"
						aria-expanded="false">Dropdown <span class="caret"></span></a>
						<ul class="dropdown-menu">
							<li><a href="#">Action</a></li>
							<li><a href="#">Another action</a></li>
							<li><a href="#">Something else here</a></li>
							<li role="separator" class="divider"></li>
							<li><a href="#">Separated link</a></li>
							<li role="separator" class="divider"></li>
							<li><a href="#">One more separated link</a></li>
						</ul></li>
				</ul>
				<form class="navbar-form navbar-left">
					<div class="form-group">
						<input type="text" class="form-control" placeholder="Search">
					</div>
					<button type="submit" class="btn btn-default">Submit</button>
				</form>
				<ul class="nav navbar-nav navbar-right">
					<li><a href="#"><%=session.getAttribute("usernumber")%></a></li>
					<li class="dropdown"><a href="#" class="dropdown-toggle"
						data-toggle="dropdown" role="button" aria-haspopup="true"
						aria-expanded="false">Dropdown <span class="caret"></span></a>
						<ul class="dropdown-menu">
							<li><a href="#">Action</a></li>
							<li><a href="#">Another action</a></li>
							<li><a href="#">Something else here</a></li>
							<li role="separator" class="divider"></li>
							<li><a href="#">Separated link</a></li>
						</ul></li>
				</ul>
			</div>
			<!-- /.navbar-collapse -->
		</div>
		<!-- /.container-fluid -->
	</nav>
         
         
  <h1 align="center" style="color: red">小超市</h1>
      <body>
    <table class="table table-bordered table-hover">
    <tbody>
        <tr>
            <th><h2>序号</h2></th>
            <th><h2>商品</h2></th>
            <th><h2>价格</h2></th>     
            <th><h2>图片</h2></th>       
        </tr>
        <c:if test="${!empty smallList }">
        <c:forEach items="${smallList }" var="product" >
            <tr>
                <td>${product.id }</td>
                <td>${product.productName }</td>
                <td>${product.productPrise }</td>
                <td><c:if test="${product.productImage !=null }">
                    <img id="images" alt="" src="/image/${product.productImage }">
                </c:if> </td>          
            </tr>
        </c:forEach>
        </c:if>
        </tbody>
    </table>
    <h2 align="left"><a href="<%=basePath%>/user/toAddProduct">加入</a></h2>
</body>
</body>
</html>

2.addProduct.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>加入商品</title>
</head>
<body>
    <form action="<%=basePath%>/user/uploadPic" method="post" enctype="multipart/form-data">
     
     <div align="center">     
                  <h1>增加商品</h1>               
      <table>
      <tr>
             <th> <h3>商品名称: </h3></th>
             <th><input type="text" name="productName" >   </th>
     </tr>
     <tr>
             <th> <h3>价格: </h3></th>
             <th><input type="text" name="productPrise" >   </th>
     </tr>
     <tr>
             <th> <h3>图片: </h3></th>
             <th><input type="file" name="file" >   </th>
     </tr>
     <tr>
             <th></th>
             <th><input type="submit" value="加入"></th>
     </tr>
      </table>
      </div>
      </form>
</body>
</html> 

  
  

猜你喜欢

转载自blog.csdn.net/yiye2017zhangmu/article/details/80835603
今日推荐