美文网首页
SSM上传图片并保存图片地址到数据库

SSM上传图片并保存图片地址到数据库

作者: 秃头哥编程 | 来源:发表于2018-11-06 22:21 被阅读0次

    说出来有点不好意思,还没写过上传图片的功能。最近接的一个外包项目因为有要用到这个功能,所以打算使用SSM实现图片上传的功能,上传好后把图片地址保存到数据库,同时在前端显示图片。

    使用maven构建项目,首先导入相关的jar,这里就放上传文件的jar配置,不然篇幅太长了,其他的还有spring相关的,mybatis,日志的,数据库的,包括servlet和jstl相关的。

          <!-- 文件上传的jar包 -->
          <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
          </dependency>
          <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
          </dependency>
    

    配置好pom.xml后,接下来就是web.xml,只需要配置dispatcherServlet就行。

    项目目录结构

    接下来就是新建数据表

    DROP TABLE IF EXISTS `product`;
    CREATE TABLE `product`  (
      `pid` int(11) NOT NULL AUTO_INCREMENT,
      `pimage` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`pid`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
    

    然后就是那一大堆配置文件,我就不写了,要注意的是在spring-web.xml中配置文件上传解析器

            <!-- 文件上传的解析器 -->
            <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <!-- 上传图片的最大尺寸 10M-->
                <property name="maxUploadSize" value="10485760"></property>
                <!-- 默认编码 -->
                <property name="defaultEncoding" value="utf-8"></property>
            </bean>
    

    紧接着是mapper文件的编写,主要有两个sql,一个是图片上传,另一个是选择所有图片

        <mapper namespace="com.codeliu.dao.ProductDao">
            <!-- 查询所有图片 -->
            <select id="list" resultType="product">
                select pid, pimage from product
            </select>
            
            <insert id="save" parameterType="product">
                insert into product(pimage) values(#{pimage})
            </insert>
        </mapper>
    

    接下来就是pojo,dao,service,controller类的编写

    首先pojo

    public class Product implements Serializable {
    
        private Integer pid;
        
        private String pimage;
    
        // set、get方法
    }
    

    其次dao

    public interface ProductDao {
        
        /**
         * 查询所有的图片
         * @return
         */
        List<Product> list();
        
        /**
         * 上传一张图片
         * @param product
         * @return
         */
        Integer save(Product product);
    }
    

    接着是service

    @Service
    public class ProductServiceImpl implements ProductService {
        
        @Autowired
        private ProductDao productDao;
    
        @Override
        public List<Product> list() {
            return productDao.list();
        }
    
        @Override
        @Transactional
        public String save(MultipartFile file, Product product, ModelMap map) throws IOException {
            
            // 保存图片的路径,图片上传成功后,将路径保存到数据库
            String filePath = "F:\\upload";
            // 获取原始图片的扩展名
            String originalFilename = file.getOriginalFilename();
            // 生成文件新的名字
            String newFileName = UUID.randomUUID() + originalFilename;
            // 封装上传文件位置的全路径
            File targetFile = new File(filePath, newFileName);
            file.transferTo(targetFile);    
            
            // 保存到数据库
            product.setPimage(newFileName);
            productDao.save(product);
            return "redirect:/listImages";
        }
    
    }
    

    最后是controller

    @Controller
    public class ProductController {
    
        @Autowired
        private ProductService productService;
        
        @RequestMapping("/listImages")
        public ModelAndView list(Model model) {
            List<Product> lists = productService.list();
            ModelAndView mav = new ModelAndView();
            mav.addObject("lists", lists);
            mav.setViewName("list");
            System.out.println(lists);
            return mav;
        }
        
        /**
         * 保存图片
         * @param file
         * @param product
         * @param map
         * @return
         */
        @RequestMapping("/save")
        public String save(MultipartFile file, Product product, ModelMap map) {
            try {
                return productService.save(file, product, map);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    

    上传图片的逻辑在service里面,注释很清楚,相信一看就能明白,接着写两个jsp页面,一个用于上传,一个用于显示。

    <body>
        <form action="save" method="post" enctype="multipart/form-data">
            图片:<input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>
    </body>
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <title>list</title>
    <style type="text/css">
        #images{
            width: 150px;
            height: 250px;
        }
    </style>
    </head>
    <body>
        
        <table class="table table-bordered table-hover">
            <tr>
                <th>序号</th>
                <th>图片</th>
            </tr>
            <c:forEach items="${lists}" var="product">
                <tr>
                    <td>${product.pid}</td>
                    <td>
                        <c:if test="${product.pimage != null}">
                            <img alt="" src="/image/${product.pimage}" id="images">
                        </c:if>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </body>
    </html>
    

    做好了上面的这些,还需要指定图片上传的位置,直接在tomcat中指定


    万事俱备,只欠东风了。接下来就启动项目,输入localhost:8080/SSM_uploadImage/index.jsp,就可以选择图片进行上传,上传之后,可以看到数据库已经插入了一条记录,同时指定的目录下已经有图片了。

    4.png

    跳转到list.jsp,显示图片

    5.png

    相关文章

      网友评论

          本文标题:SSM上传图片并保存图片地址到数据库

          本文链接:https://www.haomeiwen.com/subject/ccypxqtx.html