文件上传下载实现持久化
文件上传接口
package hr.com.web.servlet;
import com.alibaba.fastjson.JSONObject;
import hr.com.common.LayuiRepResult;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("FileUploadServlet------");
// 获取已上传的文件名列表
List<String> fileNames = (List<String>) request.getSession().getAttribute("uploadedFiles");
if (fileNames == null) {
fileNames = new ArrayList<>();
request.getSession().setAttribute("uploadedFiles", fileNames); // 在此处保存空列表到会话中
}
// 获取上传的文件列表
for (Part part : request.getParts()) {
if (part.getSubmittedFileName() != null) {
String fileName = part.getSubmittedFileName();
String uniqueFileName = generateUniqueFileName(fileName);
try (InputStream fileContent = part.getInputStream()) {
String realPath = request.getServletContext().getRealPath("/upload/");
System.out.println("realPath="+realPath);
File file = new File(realPath);
file.mkdirs();
Files.copy(fileContent, new File(realPath + uniqueFileName).toPath(), StandardCopyOption.REPLACE_EXISTING);
fileNames.add(uniqueFileName);
} catch (IOException e) {
e.printStackTrace();
response.getWriter().write(JSONObject.toJSONString(LayuiRepResult.error("上传失败")));
return;
}
}
}
System.out.println("fileNames="+fileNames);
// 将文件名列表保存到会话中
request.getSession().setAttribute("uploadedFiles", fileNames);
response.getWriter().write(JSONObject.toJSONString(LayuiRepResult.success("上传成功",fileNames)));
}
private String generateUniqueFileName(String fileName) {
String extension = "";
int dotIndex = fileName.lastIndexOf(".");
if (dotIndex >= 0) {
extension = fileName.substring(dotIndex);
}
return UUID.randomUUID().toString().replace("-", "") + extension;
}
}
文件下载
package hr.com.web.servlet;
import com.alibaba.fastjson.JSONObject;
import hr.com.common.LayuiRepResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/download")
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取请求参数中的文件名
String fileName = request.getParameter("filename");
System.out.println("filename="+fileName);
if (fileName == null || fileName.isEmpty()) {
response.getWriter().write(JSONObject.toJSONString(LayuiRepResult.error("Invalid file name")));
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// 获取文件的实际路径
String realPath = request.getServletContext().getRealPath("/upload/");
String filePath = realPath + fileName;
File file = new File(filePath);
// 检查文件是否存在
if (!file.exists()) {
response.getWriter().write(JSONObject.toJSONString(LayuiRepResult.error("File not found")));
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 将文件内容写入响应输出流
try (FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
response.getWriter().write(JSONObject.toJSONString(LayuiRepResult.error("Error occurred while downloading the file")));
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
response.getWriter().write(JSONObject.toJSONString(LayuiRepResult.success("文件下载成功")));
}
}
监听器
文件上传到服务器中的upload文件夹中,文件下载从数据库中获取文件名,然后然后加上upload文件路径,实现持久化是才服务器关闭时,将服务器中upload的文件备份到项目的resources/static中,然后在服务器启动的时候,将resources/static中的备份文件给加载到服务器中的upload (要提前在resources目录下面创建static)
package hr.com.web.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@WebListener
public class FileBackupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("WebListener contextInitialized ");
// 应用程序启动时的初始化操作 获取服务器中upload文件夹路径
String realPath = sce.getServletContext().getRealPath("/upload/");
System.out.println("/upload/ realPath="+realPath);
//这是绝对路径,根据自己项目路径进行修改
String realPath1 = "D:/idea-code/hrSystem/src/main/resources/static/";
File file = new File(realPath);
file.mkdirs();
restoreFiles(realPath,realPath1);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("WebListener contextDestroyed ");
// 应用程序关闭时的清理操作 获取服务器中upload文件夹路径
String realPath = sce.getServletContext().getRealPath("/upload/");
System.out.println("/upload/ realPath="+realPath);
//这是绝对路径,根据自己项目路径进行修改
String realPath1 = "D:/idea-code/hrSystem/src/main/resources/static/";
System.out.println("realPath1="+realPath1);
File file = new File(realPath);
file.mkdirs();
backupFiles(realPath,realPath1);
}
private void backupFiles(String realPath,String real) {
String sourceDirectoryPath = realPath; // 上传文件存储的目录
String destinationDirectoryPath = real ; // 静态资源目录
try {
// 复制文件到静态资源目录
Files.walk(new File(sourceDirectoryPath).toPath())
.filter(Files::isRegularFile)
.forEach(source -> {
Path destination = new File(destinationDirectoryPath, source.getFileName().toString()).toPath();
try {
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void restoreFiles(String realPath,String real) {
String uploadDirectoryPath = realPath;
String staticDirectoryPath = real;
try {
Files.walk(Paths.get(staticDirectoryPath))
.filter(Files::isRegularFile)
.forEach(filePath -> {
try {
Path destination = Paths.get(uploadDirectoryPath + filePath.getFileName());
Files.copy(filePath, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
依赖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>hr.com</groupId>
<artifactId>hrSystem</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>hrSystem Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--Mysql数据库JDBC依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<!--beanutils 把Map数据取出存入到User对象 -->
<!-- Commons BeanUtils 是 Apache Commons 项目的一-->
<!-- 部分,提供了一套用于操作 JavaBean 的工具类。它包括了-->
<!-- 一系列用于复制、克隆、比较 JavaBean 等操作的工具方法,-->
<!-- 使得在 Java 应用程序中更容易地处理 JavaBean 对象。-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<!--fastjson处理json依赖jackson处理json依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.22</version>
</dependency>
<!-- 提供了一系列用于开发 JSP 的标准标签-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--log4j日志处理依赖-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--验证码生成工具-->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 实用的 IO 工具类,用于简化 Java IO 操作。常见的文件操作、-->
<!-- 流操作等都可以通过 Commons IO 来更方便地实现。-->
<!-- 使用这个依赖项可以让你在项目中使用 Commons IO 提供的各种功能,-->
<!-- 而不需要手动下载、管理这些库文件-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.24</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<finalName>hrSystem</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>