springboot上传文件前后端
时间: 2025-05-17 08:12:53 浏览: 17
### Spring Boot 文件上传前后端实现示例
#### 前端部分
前端可以通过HTML页面中的`<input>`标签来选择文件,并通过AJAX请求将文件发送到后端服务器。为了简化操作,可以使用JavaScript库(如jQuery)来处理异步通信。
以下是前端代码的示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput" style="display:none;" />
<button type="button" onclick="$('#fileInput').trigger('click');">Select File</button>
<button type="button" onclick="uploadFile()">Upload</button>
</form>
<script>
function uploadFile() {
var formData = new FormData();
var file = $('#fileInput')[0].files[0];
if (!file) {
alert("Please select a file first.");
return;
}
formData.append("file", file);
$.ajax({
url: '/upload', // 后端接收路径
method: 'POST',
data: formData,
contentType: false, // 不设置内容类型
processData: false, // 防止 jQuery 自动转换数据
success: function(response) {
alert("File uploaded successfully!");
},
error: function(error) {
console.error("Error uploading file:", error);
}
});
}
</script>
</body>
</html>
```
上述代码实现了文件的选择和上传功能[^1]。当用户点击“Select File”按钮时,会触发隐藏的`<input>`控件;随后,用户可以选择要上传的文件并提交表单。
---
#### 后端部分
在Spring Boot中,可以通过控制器方法接收来自前端的文件流,并将其保存到指定位置。以下是一个完整的后端实现示例:
##### 添加依赖项
确保项目中已引入必要的Maven或Gradle依赖项。对于文件上传功能,通常需要以下依赖项:
```xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
##### 配置文件
配置数据库连接和其他参数(如果涉及存储元数据)。例如,在`application.properties`中定义如下属性:
```properties
# 数据源配置 (可选)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
# 文件上传临时目录大小限制
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
```
此配置允许最大上传文件大小为10MB[^4]。
##### 控制器代码
创建一个用于处理文件上传的RESTful接口:
```java
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/api/files")
public class FileController {
private static final String UPLOAD_DIR = System.getProperty("user.dir") + "/uploads/";
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "Failed to upload empty file.";
}
try {
// 创建目标目录
File dir = new File(UPLOAD_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
// 将文件写入磁盘
byte[] bytes = file.getBytes();
File targetFile = new File(dir.getAbsolutePath() + "/" + file.getOriginalFilename());
targetFile.createNewFile();
java.nio.file.Files.write(targetFile.toPath(), bytes);
return "File uploaded successfully!";
} catch (IOException e) {
e.printStackTrace();
return "Failed to upload file due to an internal server error.";
}
}
}
```
该代码片段展示了如何通过`@RequestParam`注解获取前端传来的文件对象,并将其保存至本地磁盘[^2]。
---
#### 测试与验证
完成上述步骤后,启动应用程序并通过浏览器访问前端页面测试文件上传功能。成功上传后,可以在指定的目标目录下找到对应的文件。
---
### 总结
本方案结合了前端HTML/AJAX技术以及Spring Boot框架的强大能力,能够高效地实现文件上传的功能需求。同时,还可以进一步扩展支持多文件上传、进度条显示等功能。
---
阅读全文
相关推荐

















