方式一:在 Web 应用中进行文件上传(后端接收)
这是最常见的场景,用户通过浏览器表单上传文件到你的 Java Web 应用。
1. 使用 Servlet API(原生方式)
这是最基础、最直接的方式,无需任何第三方库。
-
核心类/接口:
HttpServletRequest,Part(Servlet 3.0+) /Apache Commons FileUpload(Servlet 2.5) -
实现步骤:
-
前端表单设置
enctype="multipart/form-data"。 -
在 Servlet 的
doPost方法中,通过request.getPart("fileFieldName")或request.getParts()获取文件部分。 -
使用
Part.write(destinationPath)将文件保存到服务器磁盘。
-
package com.xsy.demo.upload;
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;
@MultipartConfig
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取文件 Part
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
// 定义保存路径
String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdir();
String filePath = uploadPath + File.separator + fileName;
// 保存文件
filePart.write(filePath);
response.getWriter().print("File uploaded successfully: " + fileName);
}
}
前端代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
<style>
/* 您的CSS样式保持不变 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, sans-serif;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f5f5f5;
padding: 20px;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 500px;
}
h1 {
text-align: center;
margin-bottom: 20px;
color: #333;
}
.upload-area {
border: 2px dashed #ccc;
border-radius: 6px;
padding: 40px 20px;
text-align: center;
margin-bottom: 20px;
cursor: pointer;
transition: border-color 0.3s;
}
.upload-area:hover {
border-color: #4a90e2;
}
.upload-area.highlight {
border-color: #4a90e2;
background-color: #f0f7ff;
}
.upload-icon {
font-size: 48px;
color: #4a90e2;
margin-bottom: 10px;
}
.file-input {
display: none;
}
.file-info {
margin: 15px 0;
font-size: 14px;
color: #666;
}
.upload-btn {
background-color: #4a90e2;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
width: 100%;
font-size: 16px;
transition: background-color 0.3s;
}
.upload-btn:hover {
background-color: #3a7bc8;
}
.upload-btn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.status {
margin-top: 15px;
padding: 10px;
border-radius: 4px;
text-align: center;
display: none;
}
.status.success {
background-color: #e6f7e6;
color: #2d7a2d;
display: block;
}
.status.error {
background-color: #ffe6e6;
color: #d32f2f;
display: block;
}
.status.progress {
background-color: #e6f3ff;
color: #0066cc;
display: block;
}
</style>
</head>
<body>
<div class="container">
<h1>文件上传</h1>
<div class="upload-area" id="uploadArea">
<div class="upload-icon">📁</div>
<p>点击选择文件或拖拽文件到此处</p>
<input type="file" id="fileInput" class="file-input" name="file">
</div>
<div class="file-info" id="fileInfo">未选择文件</div>
<button class="upload-btn" id="uploadBtn" disabled>上传文件</button>
<div class="status" id="status"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const uploadBtn = document.getElementById('uploadBtn');
const status = document.getElementById('status');
// 点击上传区域触发文件选择
uploadArea.addEventListener('click', function() {
fileInput.click();
});
// 文件选择变化
fileInput.addEventListener('change', function() {
if (this.files.length > 0) {
const file = this.files[0];
fileInfo.textContent = '已选择: ' + file.name + ' (' + formatFileSize(file.size) + ')';
uploadBtn.disabled = false;
} else {
fileInfo.textContent = '未选择文件';
uploadBtn.disabled = true;
}
hideStatus();
});
// 拖放功能
uploadArea.addEventListener('dragover', function(e) {
e.preventDefault();
uploadArea.classList.add('highlight');
});
uploadArea.addEventListener('dragleave', function() {
uploadArea.classList.remove('highlight');
});
uploadArea.addEventListener('drop', function(e) {
e.preventDefault();
uploadArea.classList.remove('highlight');
if (e.dataTransfer.files.length > 0) {
fileInput.files = e.dataTransfer.files;
const file = fileInput.files[0];
fileInfo.textContent = '已选择: ' + file.name + ' (' + formatFileSize(file.size) + ')';
uploadBtn.disabled = false;
hideStatus();
}
});
// 上传文件
uploadBtn.addEventListener('click', function() {
if (fileInput.files.length === 0) {
showStatus('请先选择文件', 'error');
return;
}
const formData = new FormData();
formData.append('file', fileInput.files[0]);
showStatus('上传中...', 'progress');
uploadBtn.disabled = true;
fetch('http://localhost:8080/upload', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('上传失败');
}
return response.text();
})
.then(data => {
showStatus('文件上传成功!', 'success');
// 重置表单
fileInput.value = '';
fileInfo.textContent = '未选择文件';
uploadBtn.disabled = true;
})
.catch(error => {
showStatus('上传失败: ' + error.message, 'error');
uploadBtn.disabled = false;
});
});
// 辅助函数:格式化文件大小
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// 辅助函数:显示状态消息
function showStatus(message, type) {
status.textContent = message;
status.className = 'status';
status.classList.add(type);
}
// 辅助函数:隐藏状态消息
function hideStatus() {
status.className = 'status';
status.style.display = 'none';
}
});
</script>
</body>
</html>
-
优点: 标准 API,无需额外依赖。
-
缺点: 功能相对基础,需要自己处理文件名冲突、文件大小限制(需在
@MultipartConfig中配置)等。
使用 Spring MVC 框架
这是目前 Java Web 开发中最主流、最推荐的方式。Spring 对文件上传做了高度封装,使用起来非常简洁。
-
核心类/接口:
MultipartFile -
实现步骤:
-
在 Spring 配置中定义一个
MultipartResolverBean(通常使用StandardServletMultipartResolver)。 -
在 Controller 的方法参数中直接使用
MultipartFile类型接收文件。 -
调用
multipartFile.transferTo(new File(path))保存文件。
-
package com.xsy.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;
/**
* 文件上传
*/
@Controller
public class UploadController {
/**
* 文件上传
* MultipartFile upload 文件上传解析器对象 解析request后,文件上传对象
* @param upload
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/fileupload.do")
public String upload(MultipartFile upload, HttpServletRequest request) throws IOException {
// 把文件上传到哪个位置
// getRealPath获取的是项目部署目录不是源代码目录 所以去target里面找
String realPath=request.getSession().getServletContext().getRealPath("/uploads");
// 创建该文件夹
File file = new File(realPath);
// 判断该文件夹是否存在
if(!file.exists()){
// 创建文件夹
file.mkdirs();
}
String originalFilename = upload.getOriginalFilename();
// 把文件的名称修改成唯一的值 随机生成一个uuid+文件名
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
originalFilename=originalFilename+"_"+uuid;
System.out.println("文件名称"+originalFilename);
System.out.println(realPath);
// 文件上传
upload.transferTo(new File(file,originalFilename));
return "suc";
}
}
前端代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<h3>文件上传</h3>
<form action="/fileupload.do" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>

2829

被折叠的 条评论
为什么被折叠?



