基于Spring MVC实现文件上传和下载
一、步骤
1.引入相关依赖pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zjd</groupId>
<artifactId>chapter13-2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-9</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring核心类-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
2.搭建Spring MVC环境(配置前端控制器)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">
<!-- 配置Spring MVC的前端配置器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 配置初始化参数,用于读取Spring MVC的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 应用加载时创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.创建Spring MVC配置文件spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置Spring MVC要扫描的包-->
<context:component-scan base-package="com.zjd"/>
<!-- 配置注解驱动-->
<mvc:annotation-driven/>
<!-- 配置静态资源的访问映射,此配置中的文件将不被前端控制器拦截-->
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 配置视图解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置请求编码格式,必须与JSP中的pageEncoding属性一致,默认为ISO-8859-1-->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 设置允许上传文件的最大值为2M,单位为字节-->
<property name="maxUploadSize" value="2097152"/>
</bean>
</beans>
4.创建files.json文件(负责记录我们上传的文件)

5.创建与files.json内容对应的资源类Resource.java
package com.zjd.pojo;
public class Resource {
private String name;
public Resource() {
}
public Resource(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
6.创建JSON工具类JSONFileUtils.java
package com.zjd.utils;
import org.apache.commons.io.IOUtils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class JSONFileUtils {
public static String readFile(String filepath) throws Exception {
FileInputStream fileInputStream = new FileInputStream(filepath);
return IOUtils.toString(fileInputStream);
}
public static void writeFile(String data, String filepath) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(filepath);
IOUtils.write(data, fileOutputStream);
}
}
7.创建文件控制类FileController.java
package com.zjd.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjd.pojo.Resource;
import com.zjd.utils.JSONFileUtils;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Controller
public class FileController {
@RequestMapping("/fileUpLoad")
public String fileUpLoad(MultipartFile[] files, HttpServletRequest request) throws Exception {
String path = request.getServletContext().getRealPath("/") + "files/";
ObjectMapper mapper = new ObjectMapper();
if (files != null && files.length > 0) {
for (MultipartFile file : files) {
String filename = file.getOriginalFilename();
ArrayList<Resource> list = new ArrayList<>();
String json = JSONFileUtils.readFile(path + "/files.json");
if (json.length() != 0) {
list = mapper.readValue(json, new TypeReference<List<Resource>>() {
});
for (Resource resource : list) {
if (filename.equals(resource.getName())) {
String[] split = filename.split("\\.");
filename = split[0] + "(1)." + split[1];
}
}
}
String filePath = path + filename;
file.transferTo(new File(filePath));
list.add(new Resource(filename));
json = mapper.writeValueAsString(list);
JSONFileUtils.writeFile(json, path + "/files.json");
}
request.setAttribute("msg", "(上传成功)");
return "forward:fileload.jsp";
}
request.setAttribute("msg", "(上传失败)");
return "forward:fileload.jsp";
}
@ResponseBody
@RequestMapping(value = "/getFilesName", produces = "text/html;character=utf-8")
public String getFilesName(HttpServletRequest request, String response) throws Exception {
String path = request.getServletContext().getRealPath("/") + "files/files.json";
String json = JSONFileUtils.readFile(path);
return json;
}
public String getFileName(HttpServletRequest request, String filename) throws Exception {
BASE64Encoder base64Encoder = new BASE64Encoder();
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
filename = "=?UTF-8?B?" + new String(base64Encoder.encode(filename.getBytes("UTF-8")) + "?=");
} else {
filename = URLEncoder.encode(filename, "UTF-8");
}
return filename;
}
@RequestMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename)throws Exception{
String path=request.getServletContext().getRealPath("/files/");
filename =new String(filename.getBytes("ISO-8859-1"),"UTF-8");
File file=new File(path+File.separator+filename);
HttpHeaders headers=new HttpHeaders();
filename=this.getFilesName(request,filename);
headers.setContentDispositionFormData("attachment",filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}
}
8.编写文件上传和下载页面fileload.jsp
<%--
Created by IntelliJ IDEA.
User: 24360
Date: 2022/12/4
Time: 16:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传与下载</title>
<script src="${pageContext.request.contextPath}/js/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<table border="1">
<tr>
<td width="200" align="center">文件上传${msg}</td>
<td width="300" align="center">下载列表</td>
</tr>
<tr>
<td height="100">
<form action="${pageContext.request.contextPath}/fileUpLoad" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple="multiple"><br/>
<input type="reset" value="清空"/>
<input type="submit" value="提交"/>
</form>
</td>
<td id="files"></td>
</tr>
</table>
</body>
<script>
$(document).ready(function () {
var url = "${pageContext.request.contextPath}/getFilesName";
$.get(url, function (files) {
var files = eval('(' + files + ')');
for (var i = 0; i < files.length; i++) {
$("#files").append("<li><a href=${pageContext.request.contextPath}" + "\\" + "download?filename=" + files[i].name + ">" + files[i].name + "</a></li>");
}
})
})
</script>
</html>
9.引入JSON脚本文件jquery.min.js

二、项目结构

三、本次完成案例:基于Spring MVC实现文件上传与下载
主要是对文件上传与下载的过程进一步了解并实现
四、重要讯息!!!!!
各位小伙伴有疑问可以私聊我,我会在每周日统一查看回复
路过的小伙伴,该篇文章如果对你有帮助,请留下你的小手(👍)再走哦,
五、下方评论区见该案例源代码
您的支持将是我一直做下去的不竭动力!!!