說(shuō)出來(lái)有點(diǎn)不好意思,還沒(méi)寫過(guò)上傳圖片的功能。最近接的一個(gè)外包項(xiàng)目因?yàn)橛幸玫竭@個(gè)功能,所以打算使用SSM實(shí)現(xiàn)圖片上傳的功能,上傳好后把圖片地址保存到數(shù)據(jù)庫(kù),同時(shí)在前端顯示圖片。
使用maven構(gòu)建項(xiàng)目,首先導(dǎo)入相關(guān)的jar,這里就放上傳文件的jar配置,不然篇幅太長(zhǎng)了,其他的還有spring相關(guān)的,mybatis,日志的,數(shù)據(jù)庫(kù)的,包括servlet和jstl相關(guān)的。
<!-- 文件上傳的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后,接下來(lái)就是web.xml,只需要配置dispatcherServlet就行。

接下來(lái)就是新建數(shù)據(jù)表
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>
<!-- 默認(rèn)編碼 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
緊接著是mapper文件的編寫,主要有兩個(gè)sql,一個(gè)是圖片上傳,另一個(gè)是選擇所有圖片
<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>
接下來(lái)就是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 {
// 保存圖片的路徑,圖片上傳成功后,將路徑保存到數(shù)據(jù)庫(kù)
String filePath = "F:\\upload";
// 獲取原始圖片的擴(kuò)展名
String originalFilename = file.getOriginalFilename();
// 生成文件新的名字
String newFileName = UUID.randomUUID() + originalFilename;
// 封裝上傳文件位置的全路徑
File targetFile = new File(filePath, newFileName);
file.transferTo(targetFile);
// 保存到數(shù)據(jù)庫(kù)
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里面,注釋很清楚,相信一看就能明白,接著寫兩個(gè)jsp頁(yè)面,一個(gè)用于上傳,一個(gè)用于顯示。
<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" />
<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>序號(hào)</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中指定


萬(wàn)事俱備,只欠東風(fēng)了。接下來(lái)就啟動(dòng)項(xiàng)目,輸入localhost:8080/SSM_uploadImage/index.jsp,就可以選擇圖片進(jìn)行上傳,上傳之后,可以看到數(shù)據(jù)庫(kù)已經(jīng)插入了一條記錄,同時(shí)指定的目錄下已經(jīng)有圖片了。

跳轉(zhuǎn)到list.jsp,顯示圖片
