目錄
引言
一、JRebel的使用
1.1.安裝JReble
1.2.反向代理工具
1.3.離線使用
二、文件上傳
2.1.公共文件跳轉(zhuǎn)
2.2.添加依賴
2.3.配置文件上傳解析器
?2.4.圖片路徑配置Tomcat
2.5.前端代碼
2.6.文件上傳實現(xiàn)
三、文件下載
3.1.Controller層
3.2.前端代碼
四、多文件上傳
4.1.Controller層
4.2.前端代碼
引言
在以往的寫代碼過程中,我們肯定會遇到客戶有文件上傳的需求,寫過的同志都知道代碼量是有的而且比較繁瑣,今天這篇博客就來介紹一個Java庫commons-fileupload,該庫是Apache的一個開源Java庫,它提供了一種簡單的方式來上傳和處理文件。它是Java Servlet API的一部分,可以方便地在Web應(yīng)用程序中實現(xiàn)文件上傳功能。
一、JRebel的使用
在講解文件上傳之前,先向大家推薦一下JRebel的使用,JRebel的主要功能是實現(xiàn)熱部署,節(jié)省了大量重啟時間,提高了個人開發(fā)效率。
1.1.安裝JReble
我這里以IDEA為例,在Settings里點擊Plugins在Marketplace處搜索jrebel,選擇第一個安裝即可。
安裝后重啟IDEA即可。
1.2.反向代理工具
這里會使用一個反向代理工具ReverseProxy_windows_amd64,而JRebel是一個Java虛擬機插件,它們之間沒有直接的關(guān)系。但是,如果您在使用JRebel時遇到了問題,可以嘗試先啟動ReverseProxy_windows_amd64,然后再使用JRebel。
下載地址
Release v1.4 · ilanyu/ReverseProxy · GitHub
下載完成后打開代理ReverseProxy_windows_amd64.exe再jrebel啟動項目
(注意:激活成功前不要關(guān)閉反向代理程序)
選擇TeamURL激活
第一行輸入http://127.0.0.1:8888/GUID
第二行輸入電子郵箱即可。
?https://www.guidgen.com/(生成GUID鏈接)
1.3.離線使用
激活后一定要手動切換到離線模式進行使用,過程如圖 如下步驟進行操作:
File ?Settings?JRebel ?Work offline ?OK
(注意點擊Work offline就會變?yōu)閃ork online)
下面就可以進行我們的SpringMVC文件上傳講解了。
二、文件上傳
2.1.公共文件跳轉(zhuǎn)
該類是方便我們少寫重復(fù)跳轉(zhuǎn)頁面的代碼需要跳什么頁面jsp的請求上加上/page即可。
@Controller
@RequestMapping("/page")
public class InputController {
@RequestMapping("{page}")
public String to(@PathVariable("page") String page){
return page;
}
@RequestMapping("/{dir}/{page}")
public String todir(@PathVariable("dir") String dir,
@PathVariable("page") String page){
return dir+"/"+page;
}
}
2.2.添加依賴
處理文件上傳的Java庫。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2.3.配置文件上傳解析器
將配置文件放入Spring-mvc.xml中
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必須和用戶JSP 的pageEncoding屬性一致,以便正確解析表單的內(nèi)容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字節(jié)) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily屬性啟用是為了推遲文件解析,以便捕獲文件大小異常-->
<property name="resolveLazily" value="true"/>
</bean>
MultipartResolver是用于處理文件上傳,當(dāng)收到請求時DispatcherServlet的checkMultipart()方法會調(diào)用MultipartResolver的isMultipart()方法判斷請求中是否包含文件,如果請求數(shù)據(jù)中包含文件,則調(diào)用MultipartResolver的resolverMultipart()方法對請求的數(shù)據(jù)進行解析,然后將文件數(shù)據(jù)解析MultipartFile并封裝在MultipartHTTPServletRequest(繼承了HTTPServletRequest)對象中,最后傳遞給Controller。 ?
?2.4.圖片路徑配置Tomcat
為了我們的后期維護,所以將本地圖片路徑與Tomcat訪問路徑進行配置文件的保存。
PropertiesUtil.java
public class PropertiesUtil {
public static String getValue(String key) throws IOException {
Properties p = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
p.load(in);
return p.getProperty(key);
}
}
resource.properties
dir=E:/oa/idea/upload/
server=/upload/
?點擊菜單欄上的Tomcat選擇Edit Configurations
2.5.前端代碼
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ 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.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>學(xué)生管理首頁</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/student/list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="sname"
placeholder="請輸入學(xué)生名稱">
<!-- <input name="rows" value="20" type="hidden"> -->
<!-- 不想分頁 -->
<%--<input name="pagination" value="false" type="hidden">--%>
</div>
<button type="submit" class="btn btn-primary mb-2">查詢</button>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/student/PreSave">新增</a>
</form>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">學(xué)生ID</th>
<th scope="col">學(xué)生名稱</th>
<th scope="col">學(xué)生照片</th>
<th scope="col">學(xué)生性別</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="s" items="${slist }">
<tr>
<td>${s.sid }</td>
<td>${s.sname }</td>
<td>
<img src="${s.sage }" style="width: 50px;height: 50px;">
</td>
<td>${s.ssex }</td>
<td>
<a href="${pageContext.request.contextPath }/student/PreSave?sid=${s.sid}">修改</a>
<a href="${pageContext.request.contextPath }/student/del?sid=${s.sid}">刪除</a>
<a href="${pageContext.request.contextPath }/page/student/upload?sid=${s.sid}">上傳照片</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- 這一行代碼就相當(dāng)于前面分頁需求前端的幾十行了 -->
<z:page pageBean="${pageBean }"></z:page>
<%--${pageBean }
${slist}--%>
</body>
</html>
upload.jsp?
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>學(xué)生照片上傳</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/student/upload" method="post" enctype="multipart/form-data">
<label>學(xué)生編號:</label><input type="text" name="sid" readonly="readonly" value="${param.sid}"/><br/>
<label>學(xué)生圖片:</label><input type="file" name="simg"/><br/>
<input type="submit" value="上傳圖片"/>
</form>
</body>
</html>
2.6.文件上傳實現(xiàn)
StudentController.java
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentBiz stubiz;
// 增
@RequestMapping("/add")
public String add(Student student){
stubiz.insertSelective(student);
return "redirect:list";
}
// 刪
@RequestMapping("/del")
public String del(Student student){
stubiz.deleteByPrimaryKey(student.getSid());
return "redirect:list";
}
// 查
@RequestMapping("/list")
public String list(Student student, HttpServletRequest request){
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
List<Student> students = stubiz.selectBySnamePager(student, pageBean);
request.setAttribute("slist",students);
request.setAttribute("pageBean",pageBean);
return "student/list";
}
// 改
@RequestMapping("/edit")
public String edit(Student student){
stubiz.updateByPrimaryKeySelective(student);
return "redirect:list";
}
// 模糊分頁查詢
@RequestMapping("/PreSave")
public String PreSave(Student student, HttpServletRequest request){
if(student!=null && student.getSid()!=null){
Student s = stubiz.selectByPrimaryKey(student.getSid());
request.setAttribute("s",s);
}
return "student/edit";
}
//文件上傳
@RequestMapping("/upload")
public String upload(MultipartFile simg,Student student) throws IOException {
//將上傳圖片保存到服務(wù)器中的指定位置
String dir= PropertiesUtil.getValue("dir");
String server=PropertiesUtil.getValue("server");
String filename = simg.getOriginalFilename();
FileUtils.copyInputStreamToFile(simg.getInputStream(),new File(dir+filename));
//將上傳的圖片保存到數(shù)據(jù)庫
student.setSage(server+ filename);
stubiz.updateByPrimaryKeySelective(student);
return "redirect:list";
}
}
效果展示:
這時候查看我們所配置的本地路徑中也有圖片了。
三、文件下載
3.1.Controller層
StudentController.java
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentBiz stubiz;
// 增
@RequestMapping("/add")
public String add(Student student){
stubiz.insertSelective(student);
return "redirect:list";
}
// 刪
@RequestMapping("/del")
public String del(Student student){
stubiz.deleteByPrimaryKey(student.getSid());
return "redirect:list";
}
// 查
@RequestMapping("/list")
public String list(Student student, HttpServletRequest request){
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
List<Student> students = stubiz.selectBySnamePager(student, pageBean);
request.setAttribute("slist",students);
request.setAttribute("pageBean",pageBean);
return "student/list";
}
// 改
@RequestMapping("/edit")
public String edit(Student student){
stubiz.updateByPrimaryKeySelective(student);
return "redirect:list";
}
// 模糊分頁查詢
@RequestMapping("/PreSave")
public String PreSave(Student student, HttpServletRequest request){
if(student!=null && student.getSid()!=null){
Student s = stubiz.selectByPrimaryKey(student.getSid());
request.setAttribute("s",s);
}
return "student/edit";
}
//文件上傳
@RequestMapping("/upload")
public String upload(MultipartFile simg,Student student) throws IOException {
//將上傳圖片保存到服務(wù)器中的指定位置
String dir= PropertiesUtil.getValue("dir");
String server=PropertiesUtil.getValue("server");
String filename = simg.getOriginalFilename();
FileUtils.copyInputStreamToFile(simg.getInputStream(),new File(dir+filename));
//將上傳的圖片保存到數(shù)據(jù)庫
student.setSage(server+ filename);
stubiz.updateByPrimaryKeySelective(student);
return "redirect:list";
}
//文件下載
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(Student student, HttpServletRequest req){
try {
//先根據(jù)文件id查詢對應(yīng)圖片信息
Student students = this.stubiz.selectByPrimaryKey(student.getSid());
String diskPath = PropertiesUtil.getValue("dir");
String reqPath = PropertiesUtil.getValue("server");
String realPath = students.getSage().replace(reqPath,diskPath);
String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
//下載關(guān)鍵代碼
File file=new File(realPath);
HttpHeaders headers = new HttpHeaders();//http頭信息
String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//設(shè)置編碼
headers.setContentDispositionFormData("attachment", downloadFileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//MediaType:互聯(lián)網(wǎng)媒介類型 contentType:具體請求中的媒體類型信息
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
3.2.前端代碼
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ 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.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>學(xué)生管理首頁</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/student/list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="sname"
placeholder="請輸入學(xué)生名稱">
<!-- <input name="rows" value="20" type="hidden"> -->
<!-- 不想分頁 -->
<%--<input name="pagination" value="false" type="hidden">--%>
</div>
<button type="submit" class="btn btn-primary mb-2">查詢</button>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/student/PreSave">新增</a>
</form>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">學(xué)生ID</th>
<th scope="col">學(xué)生名稱</th>
<th scope="col">學(xué)生照片</th>
<th scope="col">學(xué)生性別</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="s" items="${slist }">
<tr>
<td>${s.sid }</td>
<td>${s.sname }</td>
<td>
<img src="${s.sage }" style="width: 50px;height: 50px;">
</td>
<td>${s.ssex }</td>
<td>
<a href="${pageContext.request.contextPath }/student/PreSave?sid=${s.sid}">修改</a>
<a href="${pageContext.request.contextPath }/student/del?sid=${s.sid}">刪除</a>
<a href="${pageContext.request.contextPath }/page/student/upload?sid=${s.sid}">上傳照片</a>
<a href="${pageContext.request.contextPath }/student/download?sid=${s.sid}">下載照片</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- 這一行代碼就相當(dāng)于前面分頁需求前端的幾十行了 -->
<z:page pageBean="${pageBean }"></z:page>
<%--${pageBean }
${slist}--%>
</body>
</html>
效果演示:?
四、多文件上傳
由于我的數(shù)據(jù)庫表中沒有存儲多個圖片的字段,就不過數(shù)據(jù)庫演示了。
4.1.Controller層
//多文件上傳
@RequestMapping("/uploads")
public String uploads(HttpServletRequest req, Student student, MultipartFile[] files){
try {
StringBuffer sb = new StringBuffer();
for (MultipartFile cfile : files) {
//思路:
//1) 將上傳圖片保存到服務(wù)器中的指定位置
String dir = PropertiesUtil.getValue("dir");
String server = PropertiesUtil.getValue("server");
String filename = cfile.getOriginalFilename();
FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
sb.append(filename).append(",");
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:list";
}
4.2.前端代碼
<a href="${pageContext.request.contextPath }/page/student/uploads">多文件上傳</a>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/student/uploads" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<button type="submit">上傳</button>
</form>
</body>
</html>
效果演示:
到這里我的分享就結(jié)束了,歡迎到評論區(qū)探討交流??!
??如果覺得有用的話還請點個贊吧 ??文章來源:http://www.zghlxwxcb.cn/news/detail-728727.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-728727.html
到了這里,關(guān)于【SpringMVC】一行代碼完成文件上傳&JRebel的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!