SpringMVC实现文件上传与下载
短信预约 -IT技能 免费直播动态提醒
本文实例为大家分享了SpringMVC实现文件上传与下载的具体代码,供大家参考,具体内容如下
0.环境准备
1.maven依赖
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- springMVC依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- 文件上传的jar包 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2.springConfig。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: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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.compass.file"></context:component-scan>
<!--声明 配置springMVC视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀:视图文件的路径-->
<property name="prefix" value="/WEB-INF/view/" />
<!--后缀:视图文件的扩展名-->
<property name="suffix" value=".jsp" />
</bean>
<!--读写JSON的支持(Jackson)-->
<mvc:annotation-driven />
<!-- 配置多媒体解析 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置字符编码集 -->
<property name="defaultEncoding" value="utf-8"> </property>
<!-- 配置文件上传大小 单位是字节 -1代表没有限制 maxUploadSizePerFile是限制每个上传文件的大小,而maxUploadSize是限制总的上传文件大小 -->
<property name="maxUploadSizePerFile" value="-1"> </property>
<!-- ,不设置默认不限制总的上传文件大小,这里设置总的上传文件大小不超过1M(1*1024*1024) -->
<property name="maxUploadSize" value="1048576"/>
</bean>
</beans>
3.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 声明springMvc的核心对象 DispatcherServlet -->
<servlet>
<servlet-name>web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springConfig.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>web</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
<!-- 注册字符集过滤器,解决post请求的中文乱码问题-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>
@Controller
public class UploadIFileController {
// 处理单个文件上传
@PostMapping("/uploadFile1.mvc")
public ModelAndView uploadFile1(MultipartFile file, HttpSession session) throws IOException {
ModelAndView view = new ModelAndView();
// 得到文件名称
String filename=file.getOriginalFilename();
System.out.println("文件名称:"+filename);
if (!file.isEmpty()){
// 判断文件的后缀
if (filename.endsWith(".jpg")||filename.endsWith(".png")||filename.endsWith(".txt"));
//设置文件的保存路径
String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\class="lazy" data-src\\main\\webapp\\WEB-INF\\file";
File class="lazy" data-srcFile = new File(savePath,filename);
// 执行文件保存操作
file.transferTo(class="lazy" data-srcFile);
view.setViewName("forward:/uploadSuccess.jsp");
}else {
view.setViewName("forward:/uploadFailed.jsp");
}
return view;
}
// 处理多文件上传
@PostMapping("/uploadFile2.mvc")
public ModelAndView uploadFile2(MultipartFile[] file,HttpSession session) throws IOException {
ModelAndView view = new ModelAndView();
//设置文件的保存路径
String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\class="lazy" data-src\\main\\webapp\\WEB-INF\\file";
String[] filenames = new String[file.length];
// 只要上传过来的文件为空或者是不符合指定类型的都会上传失败
for (int i = 0; i <filenames.length ; i++) {
// 判断上传过来的文件是否为空
if (!file[i].isEmpty()){
String filename=file[i].getOriginalFilename();
// 判断文件类型
if (filename.endsWith(".txt")||filename.endsWith(".jpg")||filename.endsWith(".png")){
// 创建一个文件对象
File class="lazy" data-srcFile = new File(savePath, filename);
// 执行保存文件操作
file[i].transferTo(class="lazy" data-srcFile);
view.setViewName("forward:/uploadSuccess.jsp");
}else {
view.setViewName("forward:/uploadSuccess.jsp");
}
}else {
view.setViewName("forward:/uploadFailed.jsp");
}
}
return view;
}
}
2.文件下载
文件下分为两种情况:
- 文件名称是纯英文字母的
- 文件名带有中文不处理会乱码的
1.前端代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件下载</title>
</head>
<body>
<h1 style="text-align: center"><a href="${pageContext.request.contextPath}/download1.mvc?filename=preview.jpg" rel="external nofollow" >文件下载(非中文名称)</a></h1>
<h1 style="text-align: center"><a href="${pageContext.request.contextPath}/download2.mvc?filename=文件下载.txt" rel="external nofollow" >文件下载(中文名称)</a></h1>
</body>
</html>
2.后端代码
@Controller
public class DownloadController {
// 非中文名称文件下载
@GetMapping("/download1.mvc")
public ResponseEntity <byte[]> fileDownload1(String filename,HttpServletRequest request) throws IOException {
String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\class="lazy" data-src\\main\\webapp\\WEB-INF\\file\\";
File file = new File(path,filename);
HttpHeaders header = new HttpHeaders();
header.setContentDispositionFormData("attachment",filename);
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
return result;
}
// 中文名称文件下载
@GetMapping("/download2.mvc")
public ResponseEntity <byte[]> fileDownload2(String filename,HttpServletRequest request) throws IOException {
System.out.println(filename);
String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\class="lazy" data-src\\main\\webapp\\WEB-INF\\file\\";
filename = filename.replace("_", "%");
filename= URLDecoder.decode(filename,"UTF-8");
String downloadFile="";
if (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie")>0){
filename= URLEncoder.encode(filename,"UTF-8");
downloadFile=filename.replaceAll("+","%20");
}else {
downloadFile=new String(filename.getBytes("UTF-8"),"ISO-8859-1");
}
File file = new File(path,filename);
HttpHeaders header = new HttpHeaders();
header.setContentDispositionFormData("attachment",downloadFile);
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
return result;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341