spring配置環境下的檔案上傳以及上傳的圖片展示
阿新 • • 發佈:2020-12-19
實現的效果目的:
把本地的圖片進行上傳,並且儲存至當前專案的tomcat伺服器和資料庫中,
當需要展示圖片的時候,我們拿資料庫中絕對路徑的相對路徑,這個時候就需
要在控制層進行絕對路徑的處理,處理完後,就可以通過相對路徑去匹配服務
器中的圖片相對路徑,然後進行展示
注意事項:
a.存入資料庫中的是決定路徑,而不是相對路徑,方便查詢圖片在電腦中存放的伺服器下的位置
b.前端頁面的file的input框的name不能和資料庫存放圖片路徑的欄位一樣
c.新增使用者資訊的時候,注意生日的日期格式,必須在實體類中birthday屬性加上註解
檔案上傳以及展示的實現步驟:
1.匯入依賴:三個jar包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<!--檔案上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
2.springmvc的springmvc-serlvet配置檔案中配置上傳檔案的配置資訊
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.smbms.controller"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/statics/**" location="/statics/"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置檔案上傳的配置資訊-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="5000000"/>
</bean>
</beans>
3.useradd3.jsp頁面需要一個file型別的input框
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<jsp:include page="/WEB-INF/jsp/common/head.jsp"/>
<div>
<h2>${uploadFileError}</h2>
${uploadFileError}
<form action="/jsp/user/addSave3" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label for="userCode">userCode</label>
<input type="text" class="form-control" id="userCode" name="userCode" value="" placeholder="使用者編碼">
</div>
<div class="form-group col-md-6">
<label for="userName">userName</label>
<input type="text" class="form-control" id="userName" name="userName" value="" placeholder="使用者暱稱">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="userPassword">userPassword</label>
<input type="password" class="form-control" id="userPassword" name="userPassword" value="" placeholder="userPassword">
</div>
<div class="form-group col-md-6">
<label for="gender">性別</label>
<input type="text" class="form-control" id="gender" name="gender" value="" placeholder="性別:1 男, 2:女">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="birthday">生日</label>
<input type="text" class="form-control" id="birthday" name="birthday" value="" placeholder="birthday">
</div>
<div class="form-group col-md-6">
<label for="phone">電話</label>
<input type="text" class="form-control" id="phone" name="phone" value="" placeholder="phone">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="address">地址</label>
<input type="text" class="form-control" id="address" name="address" value="" placeholder="address">
</div>
<div class="form-group col-md-6">
<label for="userRole">使用者角色</label>
<input type="text" class="form-control" id="userRole" name="userRole" value="" placeholder="userRole">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="idPicPath_a">個人身份證件照上傳</label>
<input type="file" class="form-control-file" id="idPicPath_a" name="multipartFiles" value=""
placeholder="選擇檔案">
</div>
<div class="form-group">
<label for="workPicPath_a">工作證件照上傳</label>
<input type="file" class="form-control-file" id="workPicPath_a" name="multipartFiles" value=""
placeholder="選擇檔案">
</div>
</div>
<input type="submit" class="btn btn-primary" value="新增"/>
</form>
</div>
<jsp:include page="/WEB-INF/jsp/common/foot.jsp"/>
4.userview3.jsp檢視詳情頁面,進行檔案上傳的圖片展示
<%--
Created by IntelliJ IDEA.
User: liujie
Date: 2020/12/18
Time: 16:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>使用者詳情展示</h1>
<div id="d_view">
使用者編碼:<input type="text" name="userCode" id="userCode" value="${user.userCode}"><br>
使用者名稱稱:<input type="text" name="userName" id="userName" value="${user.userName}"><br>
使用者密碼: <input type="password" name="userPassword" id="userPassword" value="${user.userPassword}">
性別:<input type="text" name="gender" id="gender" value="${user.gender}"><br>
生日:<input type="text" name="birthday" id="birthday" value="${user.birthday}">
電話:<input type="text" name="phone" id="phone" value="${user.phone}"><br>
使用者角色:<input type="text" name="userRole" id="userRole" value="${user.userRole}"><br>
個人證件照片:<img src="${pageContext.request.contextPath}/statics/uploadfiles/${idPicRelPath}"> <br>
個人工作證件照:<img src="${pageContext.request.contextPath}/statics/uploadfiles/${workPicRelPath}"> <br>
<a href="javaScript:void(0);" id="view_return">返回</a>
</div>
</body>
</html>
5.userController類中的addSave方法行為中實現多檔案上傳
/**
* 多檔案上傳
* multipartFiles[]型別的引數是和頁面的file型別的input框繫結的
* 通過註解@RequestParam("multipartFiles")鎖定進行獲取檔案上
* 傳的name="multipartFiles"的標籤中的資訊
* @param model
* @param request
* @param user
* @param multipartFiles
* @return
*/
@RequestMapping("addSave3")
public String addSave3(Model model
,HttpServletRequest request
,User user
,@RequestParam("multipartFiles")MultipartFile[] multipartFiles){
if(multipartFiles.length>0){
for (int i=0;i<multipartFiles.length;i++){
String idPicPath=null;
String workPicPath=null;
if(!multipartFiles[i].isEmpty()){
//獲取伺服器路徑
String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
//獲取原檔名
String originalFilename = multipartFiles[i].getOriginalFilename();
//獲取字尾名
String suffix = FilenameUtils.getExtension(originalFilename);
//設定圖片上傳的大小限制
Integer fileSize=1024*1000;
if(multipartFiles[i].getSize()>fileSize){
model.addAttribute("uploadError","* 檔案上傳大小不能大於1mb");
return "user/useradd3";
}else if("jpg".equals(suffix)||"png".equals(suffix)
||"jpeg".equals(suffix)||"pneg".equals(suffix)){
String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"Personal.png";
File targetFile = new File(path,fileName);
if(!targetFile.exists()){
//遞迴建立一個檔案
targetFile.mkdirs();
}
//進行檔案上傳
try {
multipartFiles[i].transferTo(targetFile);
if(i==0){
idPicPath=path+File.separator+fileName;
user.setIdPicPath(idPicPath);
}
if(i==1){
workPicPath=path+File.separator+fileName;
user.setWorkPicPath(workPicPath);
}
} catch (IOException e) {
e.printStackTrace();
}
}else{
model.addAttribute("uploadError","* 上傳的圖片格式不正確");
}
}
}
}
//呼叫userService的userAdd方法進行使用者新增
int count = userService.userAdd(user);
if(count>0){
return "redirect:/jsp/user/query2";
}
model.addAttribute("uploadError","* 新增失敗");
return "user/useradd3";
}
6.userController類中的selectById3方法行為中進行使用者詳情的展示,並且展示上傳檔案的圖片
/**
* 使用者的檢視詳情
* @param model
* @param id
* @param request
* @return
*/
@RequestMapping("selectById3")
public String selectById3(Model model
,Long id
,HttpServletRequest request){
User user = userService.queryUserById(id);
//處理資料庫儲存的絕對路徑
String idPicPath = user.getIdPicPath();
String workPicPath = user.getWorkPicPath();
String[] arridPicPath = idPicPath.split("\\\\");
String[] arrworkPicPath = workPicPath.split("\\\\");
String idPicRelPath=arridPicPath[arridPicPath.length-1];
String workPicRelPath=arrworkPicPath[arrworkPicPath.length-1];
model.addAttribute("idPicRelPath",idPicRelPath);
model.addAttribute("workPicRelPath",workPicRelPath);
model.addAttribute("user",user);
return "user/userview3";
}
7.效果截圖
1)------>使用者新增頁面
2)------>點選選擇檔案後
3)------->點選新增去userList3.jsp頁面,然後點選尾頁的最後一條資料
4)-------->點選檢視詳情,進行上傳檔案的圖片展示成功
8.最後
文章有點長,如果你耐心地看到這,也相信你會有點收穫,作者會持續進行更新,還望你的小小關注走一走