springMVC配置環(huán)境實(shí)現(xiàn)文件上傳和下載
最近的項(xiàng)目中用到了文件的上傳和下載功能,我覺(jué)著這個(gè)功能比較重要,因此特意把它提取出來(lái)自己進(jìn)行了嘗試。
下面就是springMVC配置環(huán)境實(shí)現(xiàn)文件上傳和下載的具體步驟,供大家參考,具體內(nèi)容如下
一、 基礎(chǔ)配置:
maven導(dǎo)包及配置pom.xml,導(dǎo)包時(shí)除開(kāi)springmvc的基礎(chǔ)依賴外,需要導(dǎo)入文件上傳下載時(shí)用到的commons-io.jsr和commons-fileupload.jar:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>filLoadTest</groupId>
<artifactId>filLoadTest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>filLoadTest Maven Webapp</name>
<url>http://maven.apache.org</url>
<build>
<finalName>filLoadTest</finalName>
<plugins>
<!-- 以下配置可以保證每次強(qiáng)制更新時(shí)jre版本不會(huì)變化,那我的eclipse4.4.1,maven3.2.5為例,如果不設(shè)置這個(gè),每次強(qiáng)制更新時(shí)jre就會(huì)變回1.5 -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<verbose />
<bootclasspath>${java.home}\lib\rt.jar</bootclasspath>
</compilerArguments>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
</project>
web.xml基礎(chǔ)配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <description>字符集過(guò)濾器</description> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>字符集編碼</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
spring基礎(chǔ)配置spring.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:annotation-config /> <mvc:annotation-driven /> <context:component-scan base-package="controllers" /> <!-- 避免IE執(zhí)行AJAX時(shí),返回JSON出現(xiàn)下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=utf-8</value> </list> </property> </bean> <!-- 啟動(dòng)Spring MVC的注解功能,完成請(qǐng)求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉(zhuǎn)換器 --> </list> </property> </bean> <!-- 支持上傳文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!-- 100M --> <property name="maxUploadSize" value="104857600"></property> <property name="defaultEncoding" value="utf-8"></property> </bean> </beans>
二、文件上傳的代碼
上傳的簡(jiǎn)單頁(yè)面index.html,要注意form表單提交時(shí)的entype的設(shè)置:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <form action="./upLoadFile.do" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="file"/> <input type="submit" value="提交"/> </form> </body> </html>
上傳對(duì)應(yīng)的后臺(tái)java代碼,具體問(wèn)題見(jiàn)注釋:
package controllers;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Controller
public class fileController {
/**
* 文件上傳
*
* @author:tuzongxun
* @Title: upLoadFile
* @param @param file
* @param @param request
* @param @throws IllegalStateException
* @param @throws IOException
* @return void
* @date Apr 28, 2016 1:22:00 PM
* @throws
*/
@RequestMapping(value = "/upLoadFile.do", method = RequestMethod.POST)
public void upLoadFile(HttpServletRequest request)
throws IllegalStateException, IOException {
// @RequestParam("file") MultipartFile file,
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判斷 request 是否有文件上傳,即多部分請(qǐng)求
if (multipartResolver.isMultipart(request)) {
// 轉(zhuǎn)換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上傳文件
MultipartFile f = multiRequest.getFile(iter.next());
if (f != null) {
// 取得當(dāng)前上傳文件的文件名稱
String myFileName = f.getOriginalFilename();
// 如果名稱不為“”,說(shuō)明該文件存在,否則說(shuō)明該文件不存在
if (myFileName.trim() != "") {
// 定義上傳路徑
String path = "C:\\Users\\tuzongxun123\\Desktop\\"
+ myFileName;
File localFile = new File(path);
f.transferTo(localFile);
}
}
}
}
}
}
當(dāng)選擇文件提交后,便會(huì)看到選中的文件被傳到了代碼中指定的位置,頁(yè)面效果圖如下

三、文件下載
文件下載需要獲取下載文件的存儲(chǔ)路徑,這里只是手動(dòng)填入,如果是在具體項(xiàng)目中,可以把文件名和上傳后的存儲(chǔ)路徑保存在數(shù)據(jù)庫(kù)中。然后增加一個(gè)文件列表的頁(yè)面展示文件名和文件路徑,然后點(diǎn)擊下載的時(shí)候把相應(yīng)的文件名和路徑傳到后臺(tái)操作。
/**
* 文件下載,需要文件名和文件地址
*
* @author:tuzongxun
* @Title: download
* @param@param name
* @param@param path
* @param@return
* @param@throws IOException
* @returnResponseEntity<byte[]>
* @date Apr 28,2016 1:21:32 PM
* @throws
*/
@RequestMapping(value = "/downLoadFile.do")
public ResponseEntity<byte[]> download(@RequestParam("name") String name,
@RequestParam("filePath") String path) throws IOException {
File file = new File(path);
HttpHeaders headers = new HttpHeaders();
String fileName = new String(name.getBytes("UTF-8"), "iso-8859-1");// 為了解決中文名稱亂碼問(wèn)題
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
Html頁(yè)面,這里只是簡(jiǎn)單的填寫(xiě)文件名和文件路徑,用form表單提交到后臺(tái),然后后臺(tái)會(huì)控制response在頁(yè)面彈出保存文件路徑的選擇框,當(dāng)然了,這里的后臺(tái)我沒(méi)有做什么處理,如果文件不存在是會(huì)報(bào)錯(cuò)的,可以進(jìn)行相應(yīng)的處理:
文件下載:
</br> </br> <form action="./downLoadFile.do"style="border:1px solid grey;width:auto;" method="post"> 文件名:<input type="text" name="name"/></br></br> 文件路徑:<input type="text" name="filePath"/></br></br> <input type="submit" value="確認(rèn)下載"/> </form>
頁(yè)面視圖如下:

如果文件不存在,報(bào)錯(cuò)如下:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
- SpringMVC+Ajax實(shí)現(xiàn)文件批量上傳和下載功能實(shí)例代碼
- MyBatis與SpringMVC相結(jié)合實(shí)現(xiàn)文件上傳、下載功能
- SpringMVC實(shí)現(xiàn)文件的上傳和下載實(shí)例代碼
- 在SpringMVC框架下實(shí)現(xiàn)文件的上傳和下載示例
- SpringMVC下實(shí)現(xiàn)Excel文件上傳下載
- SpringMVC框架實(shí)現(xiàn)圖片上傳與下載
- SpringMVC實(shí)現(xiàn)文件上傳和下載功能
- SpringMVC實(shí)現(xiàn)文件上傳和下載的工具類
- SpringMvc3+extjs4實(shí)現(xiàn)上傳與下載功能
- SpringMVC實(shí)現(xiàn)上傳下載文件
相關(guān)文章
Java利用正則表達(dá)式提取數(shù)據(jù)的方法
最近由于項(xiàng)目需求需要提取txt里的數(shù)據(jù),之前用C#實(shí)現(xiàn)過(guò),由于最近學(xué)習(xí)了java,所以嘗試用java實(shí)現(xiàn)下,這篇文章主要介紹了Java利用正則表達(dá)式提取數(shù)據(jù)的方法,需要的朋友可以參考下,下面來(lái)一起看看吧。2016-12-12
關(guān)于SpringMVC在Controller層方法的參數(shù)解析詳解
在SpringMVC中,控制器Controller負(fù)責(zé)處理由DispatcherServlet分發(fā)的請(qǐng)求,下面這篇文章主要給大家介紹了關(guān)于SpringMVC在Controller層方法的參數(shù)解析的相關(guān)資料,需要的朋友可以參考下2021-12-12
SpringBoot使用Flyway進(jìn)行數(shù)據(jù)庫(kù)管理的操作方法
Flyway是一個(gè)開(kāi)源的數(shù)據(jù)庫(kù)版本管理工具,并且極力主張“約定大于配置”,簡(jiǎn)單、專注、強(qiáng)大。接下來(lái)通過(guò)本文給大家介紹SpringBoot使用Flyway進(jìn)行數(shù)據(jù)庫(kù)管理的方法,感興趣的朋友一起看看吧2021-09-09
SpringCloud?服務(wù)注冊(cè)中的nacos實(shí)現(xiàn)過(guò)程
這篇文章主要介紹了SpringCloud?服務(wù)注冊(cè)之nacos實(shí)現(xiàn)過(guò)程,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03
Java中 URL實(shí)現(xiàn)斷點(diǎn)下載
Java中 URL實(shí)現(xiàn)斷點(diǎn)下載,需要的朋友可以參考一下2013-03-03

