Spring?MVC異步上傳、跨服務(wù)器上傳和文件下載功能實(shí)現(xiàn)
一、異步上傳
之前的上傳方案,在上傳成功后都會(huì)跳轉(zhuǎn)頁面。而在實(shí)際開發(fā)中,很多情況下上傳后不進(jìn)行跳轉(zhuǎn),而是進(jìn)行頁面的局部刷新,比如:上傳頭像成功后將頭像顯示在網(wǎng)頁中。這時(shí)候就需要使用異步文件上傳。
1.1 JSP頁面
編寫JSP頁面,引入jQuery和jQuery表單上傳工具jquery.form.js【該js文件已經(jīng)上傳到我的資源,有需要的小伙伴可以自行下載】
upload4.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上傳</title>
<script src="/js/jquery-2.1.1.min.js"></script>
<script src="/js/jquery.form.js"></script>
</head>
<body>
<h3>文件上傳</h3>
<form id="ajaxForm" enctype="multipart/form-data">
<input type="file" name="file"/>
<%-- 按鈕類型不能是submit,否則會(huì)刷新頁面 --%>
<input type="button" value="上傳頭像" id="btn"/>
<!-- 上傳頭像后展示的位置 -->
<img src="/" width="100" id="img">
<script>
$(function () {
$("#btn").click(function () {
// 異步提交表單
$("#ajaxForm").ajaxSubmit({
url: "/fileUpload4",
type: "post",
success: function (data) {
$("#img").attr("src", data);
console.log(data);
}
})
})
})
</script>
</form>
</body>
</html>1.2 控制器方法
// 接收異步上傳請求
@RequestMapping("/fileUpload4")
// 不進(jìn)行頁面跳轉(zhuǎn)
@ResponseBody
public String upload3(HttpServletRequest request,MultipartFile file) throws Exception{
// 1.設(shè)置上傳文件保存的文件夾,存放上傳的文件
String realPath = request.getSession().getServletContext().getRealPath("/upload");
File dir = new File(realPath);
if(!dir.exists()){
dir.mkdirs();
}
// 拿到上傳文件名
String filename = file.getOriginalFilename();
filename = UUID.randomUUID()+"_"+filename;
// 創(chuàng)建空文件
File newFile = new File(dir,filename);
// 將上傳的文件寫到空文件中
file.transferTo(newFile);
System.out.println("/upload/"+filename);
return "/upload/"+filename;
}1.3 測試結(jié)果
訪問路徑:http://localhost:8080/upload4.jsp

OK,我們可以看得出來確實(shí)只刷新了頭像那一部分的頁面。本次案例成功實(shí)現(xiàn)
二、跨服務(wù)器上傳

由于文件占據(jù)磁盤空間較大,在實(shí)際開發(fā)中往往會(huì)將文件上傳到其他服務(wù)器中,此時(shí)需要使用跨服務(wù)器上傳文件。
2.1 修改tomcat的部分配置
1. 解壓tomcat作為圖片服務(wù)器,在tomcat的webapps下創(chuàng)建upload目錄作為文件上傳目錄。

這是我自己的tomcat安裝目錄,新建一個(gè)upload文件夾。
2. 修改tomcat的 conf/web.xml 文件,支持跨服上傳。
<servlet>
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
</servlet>3. 修改tomcat的 conf/server.xml 文件,修改tomcat端口,修改完開啟tomcat服務(wù)器,如下圖:
<Connector port="8081" protocol="HTTP/1.1"connectionTimeout="20000" redirectPort="8443" />

雙擊運(yùn)行

出現(xiàn)該頁面,不要關(guān)閉這個(gè)頁面!??!
2.2 JSP頁面
這里的內(nèi)容和上面的JSP沒有區(qū)別!只是響應(yīng)的路徑不一樣。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上傳</title>
<script src="/js/jquery-2.1.1.min.js"></script>
<script src="/js/jquery.form.js"></script>
</head>
<body>
<h3>文件上傳</h3>
<form id="ajaxForm" enctype="multipart/form-data">
<input type="file" name="file"/>
<%-- 按鈕類型不能是submit,否則會(huì)刷新頁面 --%>
<input type="button" value="上傳頭像" id="btn"/>
<!-- 上傳頭像后展示的位置 -->
<img src="/" width="100" id="img">
<script>
$(function () {
$("#btn").click(function () {
// 異步提交表單
$("#ajaxForm").ajaxSubmit({
url: "/fileUpload5",
type: "post",
success: function (data) {
$("#img").attr("src", data);
console.log(data);
}
})
})
})
</script>
</form>
</body>
</html>2.3 添加依賴
這里我們需要在pom.xml添加跨服上傳依賴
<!-- 跨服上傳 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>2.4 控制器方法
創(chuàng)建控制器方法,該方法在接受到上傳請求后將文件保存到其他服務(wù)器上。
// 該方法接收到上傳請求后將文件保存到其他服務(wù)器上
@RequestMapping("/fileUpload5")
@ResponseBody
public String upload4(HttpServletRequest request,MultipartFile file) throws Exception{
// 設(shè)置跨服上傳的服務(wù)器路徑
String path = "http://localhost:8081/upload/";
// 獲取上傳的文件名
String filename = file.getOriginalFilename();
filename = UUID.randomUUID()+"_"+filename;
// 跨服上傳:
// 1.創(chuàng)建客戶端對象
Client client = Client.create();
// 2.使用客戶端對象連接圖片服務(wù)器
WebResource resource = client.resource(path+filename);
// 3.傳輸數(shù)據(jù)
resource.put(file.getBytes());
System.out.println(path+filename);
return path+filename;
}2.5 測試結(jié)果
訪問路徑:http://localhost:8080/upload5.jsp

可以看得到確實(shí)成功上傳到了服務(wù)器上面的upload目錄下
三、文件下載
將文件上傳到服務(wù)器后,有時(shí)我們需要讓用戶下載上傳的文件,接下來我們編寫文件下載功能:
3.1 查詢可下載文件方法
編寫控制器方法,查詢所有可下載的文件(我這里是查詢存放在/webapps/upload/目錄下的圖片),并跳轉(zhuǎn)到下載頁面
// 查詢可下載的文件
@RequestMapping("/showFiles")
public String showFileDown(HttpServletRequest request, Model model){
// 1.獲取下載文件路徑集合。注:跨服務(wù)器上傳中,網(wǎng)絡(luò)路徑無法獲取文件列表。
String path = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(path);
String [] files = file.list();
// 2.將路徑放入模型中,跳轉(zhuǎn)到JSP頁面
model.addAttribute("files",files);
return "download";
}3.2 添加JSTL依賴
<!-- 添加JSTL依賴 -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>3.3 編寫下載頁面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>下載</title>
</head>
<body>
<h3>文件下載</h3>
<%-- 遍歷文件集合 --%>
<c:forEach items="${files}" var="file">
<a href="/download?fileName=${file}" rel="external nofollow" >${file}</a><br/>
</c:forEach>
</body>
</html>3.4 下載控制器方法
// 文件下載
@RequestMapping("/download")
public void fileDown(HttpServletRequest request, HttpServletResponse response,String fileName) throws Exception{
// 設(shè)置響應(yīng)頭
response.setHeader("Content-Disposition","attachment;filename="+fileName);
// 獲取文件路徑
String path = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(path,fileName);
// 獲取字節(jié)輸出流
ServletOutputStream os = response.getOutputStream();
// 使用輸出流寫出文件
os.write(FileUtils.readFileToByteArray(file));
os.flush();
os.close();
}3.5 測試結(jié)果
OK,我們先來訪問http://localhost:8080/showFiles
查詢出所有可以下載的文件:然后點(diǎn)擊下載也是可以成功下載,文件的上傳和下載就學(xué)習(xí)到這里了。

到此這篇關(guān)于Spring MVC異步上傳、跨服務(wù)器上傳和文件下載的文章就介紹到這了,更多相關(guān)Spring MVC文件上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMVC跨服務(wù)器上傳文件中出現(xiàn)405錯(cuò)誤的解決
這篇文章主要介紹了SpringMVC跨服務(wù)器上傳文件中出現(xiàn)405錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
SpringBoot整合Swagger和Actuator的使用教程詳解
Swagger 是一套基于 OpenAPI 規(guī)范構(gòu)建的開源工具,可以幫助我們設(shè)計(jì)、構(gòu)建、記錄以及使用 Rest API。本篇文章主要介紹的是SpringBoot整合Swagger(API文檔生成框架)和SpringBoot整合Actuator(項(xiàng)目監(jiān)控)使用教程。感興趣的朋友一起看看吧2019-06-06
從ElasticSearch中刪除數(shù)據(jù)的幾種常見方式
這篇文章主要給大家介紹了關(guān)于從ElasticSearch中刪除數(shù)據(jù)的幾種常見方式,在Elasticsearch中刪除數(shù)據(jù)可以通過刪除索引或刪除文檔兩種方式實(shí)現(xiàn),需要的朋友可以參考下2024-10-10
解決SpringBoot項(xiàng)目啟動(dòng)成功但接口訪問404的問題
這篇文章主要介紹了如何解決SpringBoot項(xiàng)目啟動(dòng)成功但接口訪問404的問題,具有很好的參考價(jià)值,希望對大家有所幫助,接下來就跟著小編一起來看看吧2023-07-07
Mybatis Log控制臺(tái)如何輸出打印SQL語句
這篇文章主要介紹了Mybatis Log控制臺(tái)如何輸出打印SQL語句,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07

