Servlet实现文件上传下载全攻略 从原理到代码详解 如何处理大文件和并发问题

引言
在Web开发中,文件上传和下载是极其常见的功能需求。无论是用户头像上传、文档管理,还是数据备份恢复,都离不开文件的传输处理。Java Servlet作为Java Web开发的基础技术,提供了强大的文件处理能力。本文将深入探讨Servlet实现文件上传下载的完整方案,从基础原理到高级优化,全面覆盖大文件处理和并发控制等关键问题。
一、Servlet文件上传原理详解
1.1 HTTP文件上传协议基础
文件上传通常通过HTTP POST请求实现,采用
multipart/form-data
编码类型。这种编码方式允许在单个请求中包含多个部分,每个部分可以是文本数据或二进制文件。
POST /upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundary7MA4YWxkTrZu0gW

——WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”username”

zhangsan
——WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”avatar”; filename=”photo.jpg”
Content-Type: image/jpeg

[二进制图片数据…]
——WebKitFormBoundary7MA4YWxkTrZu0gW–
1.2 Servlet处理上传的两种方式
1.2.1 传统方式(Servlet 3.0之前)
在Servlet 3.0之前,需要使用第三方库如Apache Commons FileUpload来解析multipart请求。
// 依赖:commons-fileupload 和 commons-io
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(“/upload”)
public class FileUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 1. 检查请求是否为multipart
if (!ServletFileUpload.isMultipartContent(request)) {
response.getWriter().write(“Error: Form must have enctype=multipart/form-data.”);
return;
}

// 2. 配置上传参数
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);

// 3. 构造临时路径存储上传的文件
String uploadPath = getServletContext().getRealPath(“”) + File.separator + “uploads”;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}

try {
// 4. 解析请求内容
List formItems = upload.parseRequest(request);

if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
// 5. 处理表单字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);

// 6. 保存文件到磁盘
item.write(storeFile);
response.getWriter().write(“Upload Successful: ” + fileName);
}
}
}
} catch (Exception ex) {
response.getWriter().write(“Upload Failed: ” + ex.getMessage());
}
}
}
1.2.2 现代方式(Servlet 3.0+)
Servlet 3.0引入了原生的multipart支持,通过注解配置,代码更简洁。
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;

@WebServlet(“/upload”)
@MultipartConfig(
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50, // 50MB
fileSizeThreshold = 1024 * 1024 * 1 // 1MB
)
public class ModernFileUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取上传的文件部分
Part filePart = request.getPart(“file”);

// 获取文件名(需要处理浏览器路径问题)
String fileName = getSubmittedFileName(filePart);

// 构建保存路径
String uploadPath = getServletContext().getRealPath(“”) +
File.separator + “uploads”;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}

// 保存文件
String filePath = uploadPath + File.separator + fileName;
try {
filePart.write(filePath);
response.getWriter().write(“Upload Successful: ” + fileName);
} catch (IOException e) {
response.getWriter().write(“Upload Failed: ” + e.getMessage());
}
}

// 处理不同浏览器返回的文件名(包含路径的问题)
private String getSubmittedFileName(Part part) {
String contentDisposition = part.getHeader(“content-disposition”);
String[] tokens = contentDisposition.split(“;”);
for (String token : tokens) {
if (token.trim().startsWith(“filename”)) {
String filename = token.substring(token.indexOf(‘=’) + 1).trim().replace(“\””, “”);
return filename.substring(filename.lastIndexOf(‘/’) + 1)
.substring(filename.lastIndexOf(‘\\’) + 1);
}
}
return “unknown”;
}
}
1.3 文件上传的底层原理
当浏览器发送multipart请求时,Servlet容器(如Tomcat)会:
接收请求
:读取HTTP请求体,识别multipart边界
解析流
:将输入流按边界分割成多个部分
创建Part对象
:每个部分对应一个Part实例
内存/磁盘缓冲
:小文件存内存,大文件临时存磁盘
暴露给Servlet
:通过
request.getPart()
或
request.getParts()
访问
二、Servlet文件下载实现
2.1 基础下载实现
文件下载通过设置HTTP响应头实现,关键响应头包括:
Content-Type
: 文件MIME类型
Content-Disposition
: 触发浏览器下载行为
Content-Length
: 文件大小
Cache-Control
: 控制缓存行为
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@WebServlet(“/download”)
public class FileDownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// 文件存储根目录
private static final String FILE_BASE_DIR = “/var/uploads”;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 1. 获取请求的文件名(必须进行安全校验!)
String fileName = request.getParameter(“file”);
if (fileName == null || fileName.trim().isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, “File name is required”);
return;
}

// 2. 安全校验:防止路径遍历攻击
if (!isSafeFileName(fileName)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, “Invalid file name”);
return;
}

// 3. 构建文件完整路径
Path filePath = Paths.get(FILE_BASE_DIR, fileName);

// 4. 检查文件是否存在且可读
if (!Files.exists(filePath) || !Files.isReadable(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, “File not found”);
return;
}

// 5. 设置响应头
response.reset();
response.setContentType(getContentType(fileName));
response.setContentLength((int) Files.size(filePath));

// 关键:设置Content-Disposition触发下载
String encodedFileName = URLEncoder.encode(fileName, “UTF-8”).replace(“+”, “%20”);
response.setHeader(“Content-Disposition”,
“attachment; filename=\”” + encodedFileName + “\”; filename*=UTF-8”” + encodedFileName);

// 6. 禁用缓存(对于动态内容)
response.setHeader(“Cache-Control”, “no-cache, no-store, must-revalidate”);
response.setHeader(“Pragma”, “no-cache”);
response.setHeader(“Expires”, “0”);

// 7. 写入文件流
try (InputStream in = Files.newInputStream(filePath);
OutputStream out = response.getOutputStream()) {

byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();

} catch (IOException e) {
// 记录日志,但客户端可能已经部分接收数据
log(“Download interrupted: ” + e.getMessage());
}
}

// 安全校验:防止路径遍历攻击
private boolean isSafeFileName(String fileName) {
// 禁止包含路径分隔符或父目录引用
return !fileName.contains(“/”) &&
!fileName.contains(“\\”) &&
!fileName.contains(“..”) &&
!fileName.startsWith(“.”);
}

// 根据扩展名获取MIME类型
private String getContentType(String fileName) {
String ext = fileName.substring(fileName.lastIndexOf(‘.’) + 1).toLowerCase();
switch (ext) {
case “jpg”: case “jpeg”: return “image/jpeg”;
case “png”: return “image/png”;
case “pdf”: return “application/pdf”;
case “doc”: return “application/msword”;
case “docx”: return “application/vnd.openxmlformats-officedocument.wordprocessingml.document”;
case “txt”: return “text/plain”;
case “zip”: return “application/zip”;
default: return “application/octet-stream”;
}
}
2.2 支持断点续传的下载实现
对于大文件下载,支持断点续传可以提升用户体验。这需要处理
Range
请求头。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@WebServlet(“/download/resume”)
public class ResumableDownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private static final String FILE_BASE_DIR = “/var/uploads”;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String fileName = request.getParameter(“file”);
if (!isSafeFileName(fileName)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}

Path filePath = Paths.get(FILE_BASE_DIR, fileName);
if (!Files.exists(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}

long fileLength = Files.size(filePath);
long rangeStart = 0;
long rangeEnd = fileLength – 1;

// 检查是否支持断点续传
String rangeHeader = request.getHeader(“Range”);
if (rangeHeader != null) {
// 解析Range头:bytes=0-499, 500-999, etc.
if (rangeHeader.startsWith(“bytes=”)) {
String range = rangeHeader.substring(6);
String[] ranges = range.split(“-“);
try {
rangeStart = Long.parseLong(ranges[0]);
if (ranges.length > 1) {
rangeEnd = Long.parseLong(ranges[1]);
} else {
rangeEnd = fileLength – 1;
}
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
}
}

// 设置响应
response.reset();
response.setStatus(rangeHeader != null ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK);
response.setContentType(getContentType(fileName));
response.setContentLength((int) (rangeEnd – rangeStart + 1));

// 设置Content-Range头(仅在部分内容时)
if (rangeHeader != null) {
response.setHeader(“Content-Range”, “bytes ” + rangeStart + “-” + rangeEnd + “/” + fileLength);
}

// 设置Content-Disposition
String encodedFileName = URLEncoder.encode(fileName, “UTF-8”).replace(“+”, “%20”);
response.setHeader(“Content-Disposition”,
“attachment; filename=\”” + encodedFileName + “\”; filename*=UTF-8”” + encodedFileName);

// 写入指定范围的数据
try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), “r”);
OutputStream out = response.getOutputStream()) {

raf.seek(rangeStart);
long bytesToRead = rangeEnd – rangeStart + 1;
byte[] buffer = new byte[8192];

while (bytesToRead > 0) {
int read = raf.read(buffer, 0, (int) Math.min(buffer.length, bytesToRead));
if (read == -1) break;
out.write(buffer, 0, read);
bytesToRead -= read;
}
out.flush();
}
}

// … isSafeFileName() 和 getContentType() 方法同上 …
}
2.3 文件下载的底层原理
文件下载的核心在于正确设置HTTP响应头,引导浏览器行为:
Content-Type
:告诉浏览器文件的类型,对于未知类型使用
application/octet-stream
会触发下载。
Content-Disposition
:
attachment
参数强制浏览器下载而不是打开,
filename
参数指定保存文件名。
Range请求
:浏览器在中断后再次请求时会带上
Range
头,服务器返回
206 Partial Content
状态码和对应字节范围。
流式传输
:使用缓冲区循环读写,避免一次性加载整个文件到内存。
三、大文件处理策略
3.1 内存优化:流式处理
问题
:一次性读取整个文件到内存会导致
OutOfMemoryError
。
解决方案
:使用缓冲区流式传输。
// 错误示范:大文件会OOM
byte[] allBytes = Files.readAllBytes(filePath); // 危险!
out.write(allBytes);

// 正确做法:流式传输
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
3.2 临时文件管理
对于上传的大文件,应优先使用磁盘临时文件而非内存。
@MultipartConfig(
maxFileSize = 1024 * 1024 * 100, // 100MB
maxRequestSize = 1024 * 1024 * 500, // 500MB
fileSizeThreshold = 1024 * 1024 * 10 // 10MB:超过10MB写入磁盘
)
public class LargeFileUploadServlet extends HttpServlet {
// 配置fileSizeThreshold后,Servlet会自动处理内存/磁盘切换
}
3.3 分片上传(前端+后端)
对于超大文件(GB级别),分片上传是最佳方案。
后端接收分片:
@WebServlet(“/upload/chunk”)
public class ChunkedUploadServlet extends HttpServlet {

private static final String CHUNK_DIR = “/var/chunks”;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取分片信息
int chunkIndex = Integer.parseInt(request.getParameter(“chunkIndex”));
int totalChunks = Integer.parseInt(request.getParameter(“totalChunks”));
String fileHash = request.getParameter(“fileHash”); // 文件唯一标识

Part chunkPart = request.getPart(“chunk”);

// 创建分片存储目录
Path chunkDir = Paths.get(CHUNK_DIR, fileHash);
if (!Files.exists(chunkDir)) {
Files.createDirectories(chunkDir);
}

// 保存分片
Path chunkPath = chunkDir.resolve(String.valueOf(chunkIndex));
try (InputStream in = chunkPart.getInputStream();
OutputStream out = Files.newOutputStream(chunkPath)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}

// 检查是否所有分片都已上传
if (isAllChunksUploaded(chunkDir, totalChunks)) {
// 合并分片
mergeChunks(chunkDir, fileHash);
// 清理临时分片
deleteChunkDir(chunkDir);
response.getWriter().write(“{\”status\”:\”complete\”}”);
} else {
response.getWriter().write(“{\”status\”:\”partial\”}”);
}
}

private boolean isAllChunksUploaded(Path chunkDir, int totalChunks) throws IOException {
for (int i = 0; i < totalChunks; i++) { if (!Files.exists(chunkDir.resolve(String.valueOf(i)))) { return false; } } return true; } private void mergeChunks(Path chunkDir, String fileHash) throws IOException { Path finalPath = Paths.get("/var/uploads", fileHash); try (OutputStream out = Files.newOutputStream(finalPath)) { for (int i = 0; ; i++) { Path chunkPath = chunkDir.resolve(String.valueOf(i)); if (!Files.exists(chunkPath)) break; byte[] chunkBytes = Files.readAllBytes(chunkPath); out.write(chunkBytes); } } } private void deleteChunkDir(Path chunkDir) throws IOException { Files.walk(chunkDir) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } } 3.4 进度监控 通过监听上传进度,可以提供更好的用户体验。 // 自定义监听器 public class ProgressListener implements WriteListener { private long bytesRead = 0; private long contentLength; private HttpServletRequest request; public ProgressListener(HttpServletRequest request, long contentLength) { this.request = request; this.contentLength = contentLength; } @TomcatGeneric // 假设使用Tomcat @Override public void onDataAvailable() throws IOException { ServletInputStream input = request.getInputStream(); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { this.bytesRead += bytesRead; // 计算进度 double progress = (double) this.bytesRead / contentLength * 100; // 可以存储到Session或Redis供前端轮询 request.getSession().setAttribute("uploadProgress", progress); } } @Override public void onAllDataRead() throws IOException { request.getSession().setAttribute("uploadProgress", 100.0); } @Override public void onError(Throwable throwable) { request.getSession().setAttribute("uploadError", throwable.getMessage()); } } // 在Servlet中使用 public class UploadWithProgressServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long contentLength = request.getContentLength(); request.setReadListener(new ProgressListener(request, contentLength)); // 处理上传... // 进度可通过Session或Redis实时获取 } } 四、并发问题处理 4.1 文件覆盖问题 场景 :多个用户同时上传同名文件。 解决方案 :使用唯一文件名或时间戳。 public class FileNameUtils { // 生成唯一文件名:原文件名_时间戳_随机数.扩展名 public static String generateUniqueFileName(String originalFileName) { String timestamp = String.valueOf(System.currentTimeMillis()); String random = String.valueOf((int)(Math.random() * 10000)); String extension = ""; int dotIndex = originalFileName.lastIndexOf('.'); if (dotIndex > 0) {
extension = originalFileName.substring(dotIndex);
}
return originalFileName.substring(0, dotIndex) + “_” + timestamp + “_” + random + extension;
}

// 使用UUID
public static String generateUUIDFileName(String originalFileName) {
String uuid = UUID.randomUUID().toString();
String extension = “”;
int dotIndex = originalFileName.lastIndexOf(‘.’);
if (dotIndex > 0) {
extension = originalFileName.substring(dotIndex);
}
return uuid + extension;
}
}
4.2 并发上传的线程安全
问题
:多个线程同时写入同一文件或目录。
解决方案
:使用锁或原子操作。
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class FileUploadLockManager {

// 使用ConcurrentHashMap存储文件锁
private static final ConcurrentHashMap fileLocks = new ConcurrentHashMap<>();

public static ReentrantLock getLock(String filePath) {
return fileLocks.computeIfAbsent(filePath, k -> new ReentrantLock());
}

public static void releaseLock(String filePath) {
fileLocks.remove(filePath);
}
}

// 在Servlet中使用
public class ConcurrentUploadServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String fileName = request.getParameter(“file”);
String filePath = “/var/uploads/” + fileName;

ReentrantLock lock = FileUploadLockManager.getLock(filePath);
lock.lock(); // 获取锁
try {
// 处理上传逻辑
Part filePart = request.getPart(“file”);
filePart.write(filePath);
} finally {
lock.unlock(); // 释放锁
FileUploadLockManager.releaseLock(filePath);
}
}
}
4.3 限流与防刷
防止恶意用户大量上传占用服务器资源。
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 限流Filter:限制每个会话的上传频率
@WebFilter(“/upload/*”)
public class UploadRateLimitFilter implements Filter {

private static final int MAX_UPLOADS_PER_MINUTE = 10;
private static final long TIME_WINDOW = 60 * 1000; // 1分钟

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();

// 获取会话上传记录
Long lastUploadTime = (Long) session.getAttribute(“lastUploadTime”);
Integer uploadCount = (Integer) session.getAttribute(“uploadCount”);

long currentTime = System.currentTimeMillis();

if (lastUploadTime == null || (currentTime – lastUploadTime) > TIME_WINDOW) {
// 新时间窗口
session.setAttribute(“lastUploadTime”, currentTime);
session.setAttribute(“uploadCount”, 1);
chain.doFilter(request, response);
} else {
// 在时间窗口内
if (uploadCount < MAX_UPLOADS_PER_MINUTE) { session.setAttribute("uploadCount", uploadCount + 1); chain.doFilter(request, response); } else { httpResponse.sendError(HttpServletResponse.SC_TOO_MANY_REQUESTS, "Upload rate limit exceeded"); } } } } 4.4 数据库事务与文件操作 问题 :文件上传成功但数据库记录失败,导致数据不一致。 解决方案 :使用补偿机制或事务协调。 public class TransactionalFileUploadService { public void uploadFileWithTransaction(Part filePart, String fileName, FileMetadata metadata) { String tempPath = "/temp/" + UUID.randomUUID() + fileName; String finalPath = "/var/uploads/" + fileName; try { // 1. 先保存到临时位置 filePart.write(tempPath); // 2. 开启数据库事务 beginTransaction(); try { // 3. 插入数据库记录 insertFileMetadata(metadata); // 4. 移动文件到最终位置(原子操作) Files.move(Paths.get(tempPath), Paths.get(finalPath), StandardCopyOption.REPLACE_EXISTING); // 5. 提交事务 commitTransaction(); } catch (Exception e) { // 6. 回滚事务 rollbackTransaction(); // 7. 删除临时文件 Files.deleteIfExists(Paths.get(tempPath)); throw new RuntimeException("Upload failed", e); } } catch (IOException e) { throw new RuntimeException("File operation failed", e); } } } 4.5 使用消息队列处理高并发 对于极高并发场景,可以使用消息队列异步处理。 // 生产者:接收上传请求 @WebServlet("/upload/async") public class AsyncUploadServlet extends HttpServlet { @Inject private MessageQueueProducer producer; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part filePart = request.getPart("file"); String fileName = getSubmittedFileName(filePart); // 将文件保存到临时存储 String tempPath = "/temp/" + UUID.randomUUID() + fileName; filePart.write(tempPath); // 发送消息到队列 UploadMessage message = new UploadMessage(tempPath, fileName, getCurrentUserId()); producer.send(message); response.getWriter().write("{\"status\":\"queued\", \"tempPath\":\"" + tempPath + "\"}"); } } // 消费者:异步处理上传 @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/upload") }) public class UploadMessageConsumer implements MessageListener { @Override public void onMessage(Message message) { try { UploadMessage uploadMsg = message.getBody(UploadMessage.class); // 移动文件到最终位置 Path tempPath = Paths.get(uploadMsg.getTempPath()); Path finalPath = Paths.get("/var/uploads", uploadMsg.getFileName()); Files.move(tempPath, finalPath, StandardCopyOption.REPLACE_EXISTING); // 更新数据库 updateFileStatus(uploadMsg.getFileName(), "COMPLETED"); } catch (Exception e) { // 记录失败,可重试或告警 log.error("Async upload failed", e); } } } 五、安全最佳实践 5.1 文件类型验证 问题 :仅检查文件扩展名不安全,可被伪造。 解决方案 :检查文件魔数(Magic Number)。 public class FileTypeValidator { // 文件魔数映射 private static final Map MAGIC_NUMBERS = new HashMap<>();
static {
MAGIC_NUMBERS.put(“JPEG”, new byte[]{(byte)0xFF, (byte)0xD8, (byte)0xFF});
MAGIC_NUMBERS.put(“PNG”, new byte[]{(byte)0x89, 0x50, 0x4E, 0x47});
MAGIC_NUMBERS.put(“PDF”, new byte[]{0x25, 0x50, 0x44, 0x46});
MAGIC_NUMBERS.put(“ZIP”, new byte[]{0x50, 0x4B, 0x03, 0x04});
}

public static boolean isValidFileType(Part filePart) throws IOException {
try (InputStream in = filePart.getInputStream()) {
byte[] header = new byte[8];
if (in.read(header) == -1) return false;

for (Map.Entry entry : MAGIC_NUMBERS.entrySet()) {
if (startsWith(header, entry.getValue())) {
return true;
}
}
}
return false;
}

private static boolean startsWith(byte[] data, byte[] prefix) {
if (prefix.length > data.length) return false;
for (int i = 0; i < prefix.length; i++) { if (data[i] != prefix[i]) return false; } return true; } } 5.2 文件名安全处理 防止路径遍历攻击和XSS攻击。 public class FileNameSanitizer { public static String sanitize(String fileName) { // 1. 移除路径分隔符 fileName = fileName.replace("/", "").replace("\\", ""); // 2. 移除父目录引用 fileName = fileName.replace("..", ""); // 3. 移除危险字符 fileName = fileName.replaceAll("[<>:\”|?*]”, “”);

// 4. 限制长度
if (fileName.length() > 255) {
fileName = fileName.substring(0, 255);
}

// 5. 如果为空,生成随机名
if (fileName.trim().isEmpty()) {
fileName = “file_” + System.currentTimeMillis();
}

return fileName;
}
}
5.3 存储位置安全
原则
:上传文件绝不存储在Web根目录下,防止直接访问。
// 错误:存储在Web根目录
String uploadPath = getServletContext().getRealPath(“https://www.oryoy.com/uploads”); // 危险!

// 正确:存储在独立目录
String uploadPath = “/var/app/uploads”; // 独立于Web应用
5.4 下载时的病毒扫描
public class VirusScanner {

public static boolean scanFile(Path filePath) {
// 调用外部杀毒软件(如ClamAV)
try {
ProcessBuilder pb = new ProcessBuilder(“clamscan”, filePath.toString());
Process process = pb.start();
int exitCode = process.waitFor();
return exitCode == 0; // 0表示无病毒
} catch (Exception e) {
log.error(“Virus scan failed”, e);
return false; // 扫描失败则拒绝
}
}
}
六、性能优化与监控
6.1 使用NIO提升性能
// 使用NIO的零拷贝技术(仅适用于下载)
public void downloadWithZeroCopy(Path filePath, HttpServletResponse response)
throws IOException {

try (FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ);
WritableByteChannel outChannel = Channels.newChannel(response.getOutputStream())) {

fileChannel.transferTo(0, fileChannel.size(), outChannel);
}
}
6.2 连接池与资源复用
对于需要多次IO操作的场景,使用连接池。
// 使用Apache Commons IO的工具类
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

// 复制流(内部使用缓冲区优化)
IOUtils.copyLarge(in, out, new byte[8192]);
6.3 监控与日志
public class MonitoredFileUploadServlet extends HttpServlet {

private static final Logger logger = Logger.getLogger(MonitoredFileUploadServlet.class.getName());

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

long startTime = System.currentTimeMillis();
String fileName = null;
long fileSize = 0;

try {
Part filePart = request.getPart(“file”);
fileName = getSubmittedFileName(filePart);
fileSize = filePart.getSize();

// 上传逻辑…

long duration = System.currentTimeMillis() – startTime;
logger.info(“Upload success: file={}, size={}, duration={}ms”,
fileName, fileSize, duration);

} catch (Exception e) {
long duration = System.currentTimeMillis() – startTime;
logger.log(Level.SEVERE, “Upload failed: file=” + fileName +
“, size=” + fileSize + “, duration=” + duration + “ms”, e);
throw new ServletException(e);
}
}
}
七、总结
Servlet文件上传下载的实现需要综合考虑多个方面:
基础实现
:Servlet 3.0+的原生支持是最简单的方式
大文件处理
:流式传输、分片上传、断点续传
并发控制
:文件锁、限流、异步队列
安全防护
:类型验证、文件名净化、存储隔离
性能优化
:NIO、缓冲区、监控
在实际项目中,建议:
小文件(<10MB):直接使用Servlet 3.0上传 中等文件(10MB-100MB):流式处理 + 临时文件 大文件(>100MB):分片上传 + 异步处理
超高并发:消息队列 + 分布式存储(如S3)
通过合理的设计和优化,Servlet可以稳定高效地处理各种文件操作场景。
# Servlet实现文件上传下载全攻略 从原理到代码详解 如何处理大文件和并发问题
引言
在Web开发中,文件上传和下载是极其常见的功能需求。无论是用户头像上传、文档管理,还是数据备份恢复,都离不开文件的传输处理。Java Servlet作为Java Web开发的基础技术,提供了强大的文件处理能力。本文将深入探讨Servlet实现文件上传下载的完整方案,从基础原理到高级优化,全面覆盖大文件处理和并发控制等关键问题。
一、Servlet文件上传原理详解
1.1 HTTP文件上传协议基础
文件上传通常通过HTTP POST请求实现,采用
multipart/form-data
编码类型。这种编码方式允许在单个请求中包含多个部分,每个部分可以是文本数据或二进制文件。
POST /upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundary7MA4YWxkTrZu0gW

——WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”username”

zhangsan
——WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”avatar”; filename=”photo.jpg”
Content-Type: image/jpeg

[二进制图片数据…]
——WebKitFormBoundary7MA4YWxkTrZu0gW–
1.2 Servlet处理上传的两种方式
1.2.1 传统方式(Servlet 3.0之前)
在Servlet 3.0之前,需要使用第三方库如Apache Commons FileUpload来解析multipart请求。
// 依赖:commons-fileupload 和 commons-io
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(“/upload”)
public class FileUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 1. 检查请求是否为multipart
if (!ServletFileUpload.isMultipartContent(request)) {
response.getWriter().write(“Error: Form must have enctype=multipart/form-data.”);
return;
}

// 2. 配置上传参数
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);

// 3. 构造临时路径存储上传的文件
String uploadPath = getServletContext().getRealPath(“”) + File.separator + “uploads”;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}

try {
// 4. 解析请求内容
List formItems = upload.parseRequest(request);

if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
// 5. 处理表单字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);

// 6. 保存文件到磁盘
item.write(storeFile);
response.getWriter().write(“Upload Successful: ” + fileName);
}
}
}
} catch (Exception ex) {
response.getWriter().write(“Upload Failed: ” + ex.getMessage());
}
}
}
1.2.2 现代方式(Servlet 3.0+)
Servlet 3.0引入了原生的multipart支持,通过注解配置,代码更简洁。
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;

@WebServlet(“/upload”)
@MultipartConfig(
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50, // 50MB
fileSizeThreshold = 1024 * 1024 * 1 // 1MB
)
public class ModernFileUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取上传的文件部分
Part filePart = request.getPart(“file”);

// 获取文件名(需要处理浏览器路径问题)
String fileName = getSubmittedFileName(filePart);

// 构建保存路径
String uploadPath = getServletContext().getRealPath(“”) +
File.separator + “uploads”;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}

// 保存文件
String filePath = uploadPath + File.separator + fileName;
try {
filePart.write(filePath);
response.getWriter().write(“Upload Successful: ” + fileName);
} catch (IOException e) {
response.getWriter().write(“Upload Failed: ” + e.getMessage());
}
}

// 处理不同浏览器返回的文件名(包含路径的问题)
private String getSubmittedFileName(Part part) {
String contentDisposition = part.getHeader(“content-disposition”);
String[] tokens = contentDisposition.split(“;”);
for (String token : tokens) {
if (token.trim().startsWith(“filename”)) {
String filename = token.substring(token.indexOf(‘=’) + 1).trim().replace(“\””, “”);
return filename.substring(filename.lastIndexOf(‘/’) + 1)
.substring(filename.lastIndexOf(‘\\’) + 1);
}
}
return “unknown”;
}
}
1.3 文件上传的底层原理
当浏览器发送multipart请求时,Servlet容器(如Tomcat)会:
接收请求
:读取HTTP请求体,识别multipart边界
解析流
:将输入流按边界分割成多个部分
创建Part对象
:每个部分对应一个Part实例
内存/磁盘缓冲
:小文件存内存,大文件临时存磁盘
暴露给Servlet
:通过
request.getPart()
或
request.getParts()
访问
二、Servlet文件下载实现
2.1 基础下载实现
文件下载通过设置HTTP响应头实现,关键响应头包括:
Content-Type
: 文件MIME类型
Content-Disposition
: 触发浏览器下载行为
Content-Length
: 文件大小
Cache-Control
: 控制缓存行为
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@WebServlet(“/download”)
public class FileDownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// 文件存储根目录
private static final String FILE_BASE_DIR = “/var/uploads”;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 1. 获取请求的文件名(必须进行安全校验!)
String fileName = request.getParameter(“file”);
if (fileName == null || fileName.trim().isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, “File name is required”);
return;
}

// 2. 安全校验:防止路径遍历攻击
if (!isSafeFileName(fileName)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, “Invalid file name”);
return;
}

// 3. 构建文件完整路径
Path filePath = Paths.get(FILE_BASE_DIR, fileName);

// 4. 检查文件是否存在且可读
if (!Files.exists(filePath) || !Files.isReadable(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, “File not found”);
return;
}

// 5. 设置响应头
response.reset();
response.setContentType(getContentType(fileName));
response.setContentLength((int) Files.size(filePath));

// 关键:设置Content-Disposition触发下载
String encodedFileName = URLEncoder.encode(fileName, “UTF-8”).replace(“+”, “%20”);
response.setHeader(“Content-Disposition”,
“attachment; filename=\”” + encodedFileName + “\”; filename*=UTF-8”” + encodedFileName);

// 6. 禁用缓存(对于动态内容)
response.setHeader(“Cache-Control”, “no-cache, no-store, must-revalidate”);
response.setHeader(“Pragma”, “no-cache”);
response.setHeader(“Expires”, “0”);

// 7. 写入文件流
try (InputStream in = Files.newInputStream(filePath);
OutputStream out = response.getOutputStream()) {

byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();

} catch (IOException e) {
// 记录日志,但客户端可能已经部分接收数据
log(“Download interrupted: ” + e.getMessage());
}
}

// 安全校验:防止路径遍历攻击
private boolean isSafeFileName(String fileName) {
// 禁止包含路径分隔符或父目录引用
return !fileName.contains(“/”) &&
!fileName.contains(“\\”) &&
!fileName.contains(“..”) &&
!fileName.startsWith(“.”);
}

// 根据扩展名获取MIME类型
private String getContentType(String fileName) {
String ext = fileName.substring(fileName.lastIndexOf(‘.’) + 1).toLowerCase();
switch (ext) {
case “jpg”: case “jpeg”: return “image/jpeg”;
case “png”: return “image/png”;
case “pdf”: return “application/pdf”;
case “doc”: return “application/msword”;
case “docx”: return “application/vnd.openxmlformats-officedocument.wordprocessingml.document”;
case “txt”: return “text/plain”;
case “zip”: return “application/zip”;
default: return “application/octet-stream”;
}
}
2.2 支持断点续传的下载实现
对于大文件下载,支持断点续传可以提升用户体验。这需要处理
Range
请求头。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@WebServlet(“/download/resume”)
public class ResumableDownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private static final String FILE_BASE_DIR = “/var/uploads”;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String fileName = request.getParameter(“file”);
if (!isSafeFileName(fileName)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}

Path filePath = Paths.get(FILE_BASE_DIR, fileName);
if (!Files.exists(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}

long fileLength = Files.size(filePath);
long rangeStart = 0;
long rangeEnd = fileLength – 1;

// 检查是否支持断点续传
String rangeHeader = request.getHeader(“Range”);
if (rangeHeader != null) {
// 解析Range头:bytes=0-499, 500-999, etc.
if (rangeHeader.startsWith(“bytes=”)) {
String range = rangeHeader.substring(6);
String[] ranges = range.split(“-“);
try {
rangeStart = Long.parseLong(ranges[0]);
if (ranges.length > 1) {
rangeEnd = Long.parseLong(ranges[1]);
} else {
rangeEnd = fileLength – 1;
}
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
}
}

// 设置响应
response.reset();
response.setStatus(rangeHeader != null ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK);
response.setContentType(getContentType(fileName));
response.setContentLength((int) (rangeEnd – rangeStart + 1));

// 设置Content-Range头(仅在部分内容时)
if (rangeHeader != null) {
response.setHeader(“Content-Range”, “bytes ” + rangeStart + “-” + rangeEnd + “/” + fileLength);
}

// 设置Content-Disposition
String encodedFileName = URLEncoder.encode(fileName, “UTF-8”).replace(“+”, “%20”);
response.setHeader(“Content-Disposition”,
“attachment; filename=\”” + encodedFileName + “\”; filename*=UTF-8”” + encodedFileName);

// 写入指定范围的数据
try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), “r”);
OutputStream out = response.getOutputStream()) {

raf.seek(rangeStart);
long bytesToRead = rangeEnd – rangeStart + 1;
byte[] buffer = new byte[8192];

while (bytesToRead > 0) {
int read = raf.read(buffer, 0, (int) Math.min(buffer.length, bytesToRead));
if (read == -1) break;
out.write(buffer, 0, read);
bytesToRead -= read;
}
out.flush();
}
}

// … isSafeFileName() 和 getContentType() 方法同上 …
}
2.3 文件下载的底层原理
文件下载的核心在于正确设置HTTP响应头,引导浏览器行为:
Content-Type
:告诉浏览器文件的类型,对于未知类型使用
application/octet-stream
会触发下载。
Content-Disposition
:
attachment
参数强制浏览器下载而不是打开,
filename
参数指定保存文件名。
Range请求
:浏览器在中断后再次请求时会带上
Range
头,服务器返回
206 Partial Content
状态码和对应字节范围。
流式传输
:使用缓冲区循环读写,避免一次性加载整个文件到内存。
三、大文件处理策略
3.1 内存优化:流式处理
问题
:一次性读取整个文件到内存会导致
OutOfMemoryError
。
解决方案
:使用缓冲区流式传输。
// 错误示范:大文件会OOM
byte[] allBytes = Files.readAllBytes(filePath); // 危险!
out.write(allBytes);

// 正确做法:流式传输
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
3.2 临时文件管理
对于上传的大文件,应优先使用磁盘临时文件而非内存。
@MultipartConfig(
maxFileSize = 1024 * 1024 * 100, // 100MB
maxRequestSize = 1024 * 1024 * 500, // 500MB
fileSizeThreshold = 1024 * 1024 * 10 // 10MB:超过10MB写入磁盘
)
public class LargeFileUploadServlet extends HttpServlet {
// 配置fileSizeThreshold后,Servlet会自动处理内存/磁盘切换
}
3.3 分片上传(前端+后端)
对于超大文件(GB级别),分片上传是最佳方案。
后端接收分片:
@WebServlet(“/upload/chunk”)
public class ChunkedUploadServlet extends HttpServlet {

private static final String CHUNK_DIR = “/var/chunks”;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取分片信息
int chunkIndex = Integer.parseInt(request.getParameter(“chunkIndex”));
int totalChunks = Integer.parseInt(request.getParameter(“totalChunks”));
String fileHash = request.getParameter(“fileHash”); // 文件唯一标识

Part chunkPart = request.getPart(“chunk”);

// 创建分片存储目录
Path chunkDir = Paths.get(CHUNK_DIR, fileHash);
if (!Files.exists(chunkDir)) {
Files.createDirectories(chunkDir);
}

// 保存分片
Path chunkPath = chunkDir.resolve(String.valueOf(chunkIndex));
try (InputStream in = chunkPart.getInputStream();
OutputStream out = Files.newOutputStream(chunkPath)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}

// 检查是否所有分片都已上传
if (isAllChunksUploaded(chunkDir, totalChunks)) {
// 合并分片
mergeChunks(chunkDir, fileHash);
// 清理临时分片
deleteChunkDir(chunkDir);
response.getWriter().write(“{\”status\”:\”complete\”}”);
} else {
response.getWriter().write(“{\”status\”:\”partial\”}”);
}
}

private boolean isAllChunksUploaded(Path chunkDir, int totalChunks) throws IOException {
for (int i = 0; i < totalChunks; i++) { if (!Files.exists(chunkDir.resolve(String.valueOf(i)))) { return false; } } return true; } private void mergeChunks(Path chunkDir, String fileHash) throws IOException { Path finalPath = Paths.get("/var/uploads", fileHash); try (OutputStream out = Files.newOutputStream(finalPath)) { for (int i = 0; ; i++) { Path chunkPath = chunkDir.resolve(String.valueOf(i)); if (!Files.exists(chunkPath)) break; byte[] chunkBytes = Files.readAllBytes(chunkPath); out.write(chunkBytes); } } } private void deleteChunkDir(Path chunkDir) throws IOException { Files.walk(chunkDir) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } } 3.4 进度监控 通过监听上传进度,可以提供更好的用户体验。 // 自定义监听器 public class ProgressListener implements WriteListener { private long bytesRead = 0; private long contentLength; private HttpServletRequest request; public ProgressListener(HttpServletRequest request, long contentLength) { this.request = request; this.contentLength = contentLength; } @TomcatGeneric // 假设使用Tomcat @Override public void onDataAvailable() throws IOException { ServletInputStream input = request.getInputStream(); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { this.bytesRead += bytesRead; // 计算进度 double progress = (double) this.bytesRead / contentLength * 100; // 可以存储到Session或Redis供前端轮询 request.getSession().setAttribute("uploadProgress", progress); } } @Override public void onAllDataRead() throws IOException { request.getSession().setAttribute("uploadProgress", 100.0); } @Override public void onError(Throwable throwable) { request.getSession().setAttribute("uploadError", throwable.getMessage()); } } // 在Servlet中使用 public class UploadWithProgressServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long contentLength = request.getContentLength(); request.setReadListener(new ProgressListener(request, contentLength)); // 处理上传... // 进度可通过Session或Redis实时获取 } } 四、并发问题处理 4.1 文件覆盖问题 场景 :多个用户同时上传同名文件。 解决方案 :使用唯一文件名或时间戳。 public class FileNameUtils { // 生成唯一文件名:原文件名_时间戳_随机数.扩展名 public static String generateUniqueFileName(String originalFileName) { String timestamp = String.valueOf(System.currentTimeMillis()); String random = String.valueOf((int)(Math.random() * 10000)); String extension = ""; int dotIndex = originalFileName.lastIndexOf('.'); if (dotIndex > 0) {
extension = originalFileName.substring(dotIndex);
}
return originalFileName.substring(0, dotIndex) + “_” + timestamp + “_” + random + extension;
}

// 使用UUID
public static String generateUUIDFileName(String originalFileName) {
String uuid = UUID.randomUUID().toString();
String extension = “”;
int dotIndex = originalFileName.lastIndexOf(‘.’);
if (dotIndex > 0) {
extension = originalFileName.substring(dotIndex);
}
return uuid + extension;
}
}
4.2 并发上传的线程安全
问题
:多个线程同时写入同一文件或目录。
解决方案
:使用锁或原子操作。
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class FileUploadLockManager {

// 使用ConcurrentHashMap存储文件锁
private static final ConcurrentHashMap fileLocks = new ConcurrentHashMap<>();

public static ReentrantLock getLock(String filePath) {
return fileLocks.computeIfAbsent(filePath, k -> new ReentrantLock());
}

public static void releaseLock(String filePath) {
fileLocks.remove(filePath);
}
}

// 在Servlet中使用
public class ConcurrentUploadServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String fileName = request.getParameter(“file”);
String filePath = “/var/uploads/” + fileName;

ReentrantLock lock = FileUploadLockManager.getLock(filePath);
lock.lock(); // 获取锁
try {
// 处理上传逻辑
Part filePart = request.getPart(“file”);
filePart.write(filePath);
} finally {
lock.unlock(); // 释放锁
FileUploadLockManager.releaseLock(filePath);
}
}
}
4.3 限流与防刷
防止恶意用户大量上传占用服务器资源。
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 限流Filter:限制每个会话的上传频率
@WebFilter(“/upload/*”)
public class UploadRateLimitFilter implements Filter {

private static final int MAX_UPLOADS_PER_MINUTE = 10;
private static final long TIME_WINDOW = 60 * 1000; // 1分钟

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();

// 获取会话上传记录
Long lastUploadTime = (Long) session.getAttribute(“lastUploadTime”);
Integer uploadCount = (Integer) session.getAttribute(“uploadCount”);

long currentTime = System.currentTimeMillis();

if (lastUploadTime == null || (currentTime – lastUploadTime) > TIME_WINDOW) {
// 新时间窗口
session.setAttribute(“lastUploadTime”, currentTime);
session.setAttribute(“uploadCount”, 1);
chain.doFilter(request, response);
} else {
// 在时间窗口内
if (uploadCount < MAX_UPLOADS_PER_MINUTE) { session.setAttribute("uploadCount", uploadCount + 1); chain.doFilter(request, response); } else { httpResponse.sendError(HttpServletResponse.SC_TOO_MANY_REQUESTS, "Upload rate limit exceeded"); } } } } 4.4 数据库事务与文件操作 问题 :文件上传成功但数据库记录失败,导致数据不一致。 解决方案 :使用补偿机制或事务协调。 public class TransactionalFileUploadService { public void uploadFileWithTransaction(Part filePart, String fileName, FileMetadata metadata) { String tempPath = "/temp/" + UUID.randomUUID() + fileName; String finalPath = "/var/uploads/" + fileName; try { // 1. 先保存到临时位置 filePart.write(tempPath); // 2. 开启数据库事务 beginTransaction(); try { // 3. 插入数据库记录 insertFileMetadata(metadata); // 4. 移动文件到最终位置(原子操作) Files.move(Paths.get(tempPath), Paths.get(finalPath), StandardCopyOption.REPLACE_EXISTING); // 5. 提交事务 commitTransaction(); } catch (Exception e) { // 6. 回滚事务 rollbackTransaction(); // 7. 删除临时文件 Files.deleteIfExists(Paths.get(tempPath)); throw new RuntimeException("Upload failed", e); } } catch (IOException e) { throw new RuntimeException("File operation failed", e); } } } 4.5 使用消息队列处理高并发 对于极高并发场景,可以使用消息队列异步处理。 // 生产者:接收上传请求 @WebServlet("/upload/async") public class AsyncUploadServlet extends HttpServlet { @Inject private MessageQueueProducer producer; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part filePart = request.getPart("file"); String fileName = getSubmittedFileName(filePart); // 将文件保存到临时存储 String tempPath = "/temp/" + UUID.randomUUID() + fileName; filePart.write(tempPath); // 发送消息到队列 UploadMessage message = new UploadMessage(tempPath, fileName, getCurrentUserId()); producer.send(message); response.getWriter().write("{\"status\":\"queued\", \"tempPath\":\"" + tempPath + "\"}"); } } // 消费者:异步处理上传 @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/upload") }) public class UploadMessageConsumer implements MessageListener { @Override public void onMessage(Message message) { try { UploadMessage uploadMsg = message.getBody(UploadMessage.class); // 移动文件到最终位置 Path tempPath = Paths.get(uploadMsg.getTempPath()); Path finalPath = Paths.get("/var/uploads", uploadMsg.getFileName()); Files.move(tempPath, finalPath, StandardCopyOption.REPLACE_EXISTING); // 更新数据库 updateFileStatus(uploadMsg.getFileName(), "COMPLETED"); } catch (Exception e) { // 记录失败,可重试或告警 log.error("Async upload failed", e); } } } 五、安全最佳实践 5.1 文件类型验证 问题 :仅检查文件扩展名不安全,可被伪造。 解决方案 :检查文件魔数(Magic Number)。 public class FileTypeValidator { // 文件魔数映射 private static final Map MAGIC_NUMBERS = new HashMap<>();
static {
MAGIC_NUMBERS.put(“JPEG”, new byte[]{(byte)0xFF, (byte)0xD8, (byte)0xFF});
MAGIC_NUMBERS.put(“PNG”, new byte[]{(byte)0x89, 0x50, 0x4E, 0x47});
MAGIC_NUMBERS.put(“PDF”, new byte[]{0x25, 0x50, 0x44, 0x46});
MAGIC_NUMBERS.put(“ZIP”, new byte[]{0x50, 0x4B, 0x03, 0x04});
}

public static boolean isValidFileType(Part filePart) throws IOException {
try (InputStream in = filePart.getInputStream()) {
byte[] header = new byte[8];
if (in.read(header) == -1) return false;

for (Map.Entry entry : MAGIC_NUMBERS.entrySet()) {
if (startsWith(header, entry.getValue())) {
return true;
}
}
}
return false;
}

private static boolean startsWith(byte[] data, byte[] prefix) {
if (prefix.length > data.length) return false;
for (int i = 0; i < prefix.length; i++) { if (data[i] != prefix[i]) return false; } return true; } } 5.2 文件名安全处理 防止路径遍历攻击和XSS攻击。 public class FileNameSanitizer { public static String sanitize(String fileName) { // 1. 移除路径分隔符 fileName = fileName.replace("/", "").replace("\\", ""); // 2. 移除父目录引用 fileName = fileName.replace("..", ""); // 3. 移除危险字符 fileName = fileName.replaceAll("[<>:\”|?*]”, “”);

// 4. 限制长度
if (fileName.length() > 255) {
fileName = fileName.substring(0, 255);
}

// 5. 如果为空,生成随机名
if (fileName.trim().isEmpty()) {
fileName = “file_” + System.currentTimeMillis();
}

return fileName;
}
}
5.3 存储位置安全
原则
:上传文件绝不存储在Web根目录下,防止直接访问。
// 错误:存储在Web根目录
String uploadPath = getServletContext().getRealPath(“https://www.oryoy.com/uploads”); // 危险!

// 正确:存储在独立目录
String uploadPath = “/var/app/uploads”; // 独立于Web应用
5.4 下载时的病毒扫描
public class VirusScanner {

public static boolean scanFile(Path filePath) {
// 调用外部杀毒软件(如ClamAV)
try {
ProcessBuilder pb = new ProcessBuilder(“clamscan”, filePath.toString());
Process process = pb.start();
int exitCode = process.waitFor();
return exitCode == 0; // 0表示无病毒
} catch (Exception e) {
log.error(“Virus scan failed”, e);
return false; // 扫描失败则拒绝
}
}
}
六、性能优化与监控
6.1 使用NIO提升性能
// 使用NIO的零拷贝技术(仅适用于下载)
public void downloadWithZeroCopy(Path filePath, HttpServletResponse response)
throws IOException {

try (FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ);
WritableByteChannel outChannel = Channels.newChannel(response.getOutputStream())) {

fileChannel.transferTo(0, fileChannel.size(), outChannel);
}
}
6.2 连接池与资源复用
对于需要多次IO操作的场景,使用连接池。
// 使用Apache Commons IO的工具类
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

// 复制流(内部使用缓冲区优化)
IOUtils.copyLarge(in, out, new byte[8192]);
6.3 监控与日志
public class MonitoredFileUploadServlet extends HttpServlet {

private static final Logger logger = Logger.getLogger(MonitoredFileUploadServlet.class.getName());

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

long startTime = System.currentTimeMillis();
String fileName = null;
long fileSize = 0;

try {
Part filePart = request.getPart(“file”);
fileName = getSubmittedFileName(filePart);
fileSize = filePart.getSize();

// 上传逻辑…

long duration = System.currentTimeMillis() – startTime;
logger.info(“Upload success: file={}, size={}, duration={}ms”,
fileName, fileSize, duration);

} catch (Exception e) {
long duration = System.currentTimeMillis() – startTime;
logger.log(Level.SEVERE, “Upload failed: file=” + fileName +
“, size=” + fileSize + “, duration=” + duration + “ms”, e);
throw new ServletException(e);
}
}
}
七、总结
Servlet文件上传下载的实现需要综合考虑多个方面:
基础实现
:Servlet 3.0+的原生支持是最简单的方式
大文件处理
:流式传输、分片上传、断点续传
并发控制
:文件锁、限流、异步队列
安全防护
:类型验证、文件名净化、存储隔离
性能优化
:NIO、缓冲区、监控
在实际项目中,建议:
小文件(<10MB):直接使用Servlet 3.0上传 中等文件(10MB-100MB):流式处理 + 临时文件 大文件(>100MB):分片上传 + 异步处理
超高并发:消息队列 + 分布式存储(如S3)
通过合理的设计和优化,Servlet可以稳定高效地处理各种文件操作场景。