以下是一个使用 Java 实现封装 PDF 附件上传功能的示例,基于常见的 Servlet 技术结合 Apache Commons FileUpload 组件(也可使用 Spring Boot 等框架简化,这里先以基础 Servlet 方式演示核心逻辑 )。示例包含前端页面(简单 HTML 表单)和后端 Java 代码处理上传:
pom.xml 中添加以下依赖(用于文件上传处理 ):<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>如果是普通 Java Web 项目,需手动下载对应 Jar 包并添加到项目类路径中。
upload.html )创建简单的 HTML 表单,用于选择 PDF 文件并提交上传:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>PDF 上传示例</title>
</head>
<body>
<h1>PDF 附件上传</h1>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="pdfFile" accept="application/pdf">
<input type="submit" value="上传">
</form>
</body>
</html>enctype="multipart/form-data" 是文件上传表单必需的,accept="application/pdf" 限制只能选择 PDF 类型文件。
UploadServlet.java )import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
public class UploadServlet extends HttpServlet {
// 上传文件保存的目录,可根据实际调整,这里设为项目下的 upload 文件夹(需提前创建或代码里判断创建)
private static final String UPLOAD_DIRECTORY = "upload";
// 内存中存储文件的阈值,超过后写入临时文件
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
// 最大文件大小
private static final long MAX_FILE_SIZE = 1024 * 1024 * 50; // 50MB
// 最大请求大小(包含文件和其他表单数据)
private static final long MAX_REQUEST_SIZE = 1024 * 1024 * 60; // 60MB
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 检查是否是multipart/form-data类型的请求
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("请求不是 multipart/form-data 类型,无法处理文件上传。");
writer.flush();
return;
}
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存阈值 - 超过后写入临时文件
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时文件存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件上传大小
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求大小(包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文处理
upload.setHeaderEncoding("UTF-8");
// 上传目录路径
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析请求获取文件项
List<FileItem> fileItems = upload.parseRequest(request);
if (fileItems != null && fileItems.size() > 0) {
for (FileItem item : fileItems) {
// 处理不在表单字段中的普通表单数据(这里主要处理文件字段)
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
// 检查文件扩展名是否为 PDF(简单校验,也可更严格判断文件内容类型等)
if (fileName.endsWith(".pdf")) {
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 保存文件到硬盘
item.write(storeFile);
response.getWriter().println("文件上传成功!文件路径:" + filePath);
} else {
response.getWriter().println("请上传 PDF 格式文件!");
}
}
}
}
} catch (Exception ex) {
response.getWriter().println("文件上传发生错误:" + ex.getMessage());
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}web.xml ,如果是传统 Java Web 项目 )<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
</web-app>如果使用 Spring Boot 框架,可利用 MultipartFile 等便捷方式实现,以下是 Spring Boot 版本的简单示例:
spring-boot-starter-web 依赖。UploadController.java )import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
public class UploadController {
// 上传文件保存的目录,可根据实际调整
private static final String UPLOAD_DIRECTORY = "upload";
@PostMapping("/upload")
public String uploadPDF(@RequestParam("pdfFile") MultipartFile file) {
// 检查文件是否为空
if (file.isEmpty()) {
return "上传文件为空,请选择文件后重试!";
}
// 检查文件是否为 PDF 格式(简单扩展名校验,也可结合文件内容类型等判断)
String fileName = file.getOriginalFilename();
if (fileName == null || !fileName.endsWith(".pdf")) {
return "请上传 PDF 格式文件!";
}
// 生成唯一文件名(避免重名)
String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;
// 构建文件保存路径
String uploadPath = System.getProperty("user.dir") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
File dest = new File(uploadPath + File.separator + uniqueFileName);
try {
// 保存文件
file.transferTo(dest);
return "文件上传成功!保存路径:" + dest.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败:" + e.getMessage();
}
}
}upload.html ,action 改为 Spring Boot 对应的接口 )<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>PDF 上传示例</title>
</head>
<body>
<h1>PDF 附件上传</h1>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
<input type="file" name="pdfFile" accept="application/pdf">
<input type="submit" value="上传">
</form>
</body>
</html>并在 application.properties 中可配置文件上传相关参数(如最大文件大小等 ):
spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=60MB上述代码分别演示了传统 Servlet 方式和 Spring Boot 方式实现 PDF 文件上传功能,核心都是接收前端上传的文件,校验文件格式(简单通过扩展名,实际可结合文件内容类型、文件头信息等更严格校验 ),然后保存到服务器指定目录。你可根据项目实际使用的框架和需求进行选择和扩展,比如添加文件上传后的后续处理(如将文件信息存入数据库记录等 ) 。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。