說出來有點不好意思,還沒寫過上傳圖片的功能。最近接的一個外包項目因為有要用到這個功能,所以打算使用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,顯示圖片

鏈接:https://www.jianshu.com/p/4d5dc6a3143f