本案例是通過springmvc+spring+mybatis框架以商品上傳為例,實現的圖片上傳功能,並把圖片的地址保存到數據庫並在前台顯示上傳的圖片。
本項目是使用maven搭建的項目,首先看下項目結構
相關配置自行搜索,下邊直接實現上傳功能
1.創建數據庫
DROP TABLE IF EXISTS `product`; CREATE TABLE `product` ( `pid` int(11) NOT NULL AUTO_INCREMENT, `pimage` varchar(255) DEFAULT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of product -- ---------------------------- INSERT INTO `product` VALUES ('2', '6c648d82-dc29-4b92-855e-491741e092a21.jpg'); INSERT INTO `product` VALUES ('3', '80f26905-7342-492c-be6e-c3f0ad81c2aa1.jpg'); INSERT INTO `product` VALUES ('4', 'c3d28f16-4b17-4568-8877-ff1fd4e514a31.jpg'); INSERT INTO `product` VALUES ('5', 'bb8070e8-5b3f-4be2-83d6-698dd6169dca');
2.創建商品實體類product
public class Product { private Integer pid; private String pimage; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPimage() { return pimage; } public void setPimage(String pimage) { this.pimage = pimage; } @Override public String toString() { return "Product [pid=" + pid + ", pimage=" + pimage + "]"; }
3.創建ProductController
@Controller public class ProductController { //注入ProductService @Autowired private ProductService productService; //查詢所有用戶 @RequestMapping("/list.do") public String listUser( Model model){ List<Product> list= productService.list(); model.addAttribute("list",list); System.out.println(list); return "list"; } /** * 保存商品 * @param image * @param product * @param map * @return * @throws IOException */ @RequestMapping("/addProduct.do") public String fileUpload(MultipartFile file,Product product, ModelMap map) throws IOException { /** * 上傳圖片 */ //圖片上傳成功后,將圖片的地址寫到數據庫 String filePath = "E:\\upload";//保存圖片的路徑 //獲取原始圖片的拓展名 String originalFilename = file.getOriginalFilename(); //新的文件名字 String newFileName = UUID.randomUUID()+originalFilename;
//封裝上傳文件位置的全路徑 File targetFile = new File(filePath,newFileName);
//把本地文件上傳到封裝上傳文件位置的全路徑 file.transferTo(targetFile); product.setPimage(newFileName); /** * 保存商品 */ productService.save(product); return "redirect:/list.do"; } }
4.創建接口ProductService
package com.ssm.service; import java.util.List; import com.ssm.entity.Product; public interface ProductService { List<Product> list(); void save(Product product); }
5.創建實現類ProductServiceImpl
@Service @Transactional public class ProductServiceImpl implements ProductService { //注入ProductMapper @Autowired private ProductMapper productMapper; @Override public List<Product> list() { return productMapper.list(); } @Override public void save(Product product) { productMapper.save(product); } }
6.創建Mapper接口
public interface ProductMapper { //保存商品 void save(Product product); //查詢商品 List<Product> list(); }
7.創建Mapper.xml
<mapper namespace="com.ssm.mapper.ProductMapper"> <!-- 添加 --> <insert id="save" parameterType="com.ssm.entity.Product" > insert into product(pimage) values (#{pimage}) </insert> <!-- 查詢用戶--> <select id="list" resultType="com.ssm.entity.Product"> select * from product </select> </mapper>
8.首頁index.jsp
<body> <form action="addProduct.do" method="post" enctype="multipart/form-data"> 圖片:<input type="file" name="file"> <input type="submit" value="提交"> </form> </body>
9.顯示列表list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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"> <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>Insert title here</title> <style type="text/css"> #images{ width: 50px; height: 50px; } </style> </head> <body> <table class="table table-bordered table-hover"> <tr> <th>序號</th> <th>圖片</th> </tr> <c:forEach items="${list}" var="product" > <tr> <th>${product.pid }</th> <th><c:if test="${product.pimage !=null }"> <img id="images" alt="" src="/image/${product.pimage }"> </c:if> </th> </tr> </c:forEach> </table> </body> </html>
最后說一下我的圖片上傳保存的位置是在本地,我是通過tomcat進行設置的,如下圖:
圖片上傳過程完成。
DROP TABLE IF EXISTS `product`;CREATE TABLE `product` ( `pid` int(11) NOT NULL AUTO_INCREMENT, `pimage` varchar(255) DEFAULT NULL, PRIMARY KEY (`pid`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ------------------------------ Records of product-- ----------------------------INSERT INTO `product` VALUES ('2', '6c648d82-dc29-4b92-855e-491741e092a21.jpg');INSERT INTO `product` VALUES ('3', '80f26905-7342-492c-be6e-c3f0ad81c2aa1.jpg');INSERT INTO `product` VALUES ('4', 'c3d28f16-4b17-4568-8877-ff1fd4e514a31.jpg');INSERT INTO `product` VALUES ('5', 'bb8070e8-5b3f-4be2-83d6-698dd6169dca');