实现文件上传需配置multipart参数并用MultipartFile接收,保存至指定目录;2. 文件下载通过UrlResource返回文件流,设置Content-Disposition响应头触发下载;3. 前端使用form表单提交测试,生产环境需增加安全校验。

在Java中实现文件上传和下载功能,通常用于Web应用中,比如Spring Boot项目。下面分别介绍如何实现文件的上传与下载,使用Spring MVC作为示例框架。
文件上传需要前端发送multipart/form-data请求,后端接收并保存文件。
步骤说明:
application.yml 配置:
立即学习“Java免费学习笔记(深入)”;
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
Controller 示例代码:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
private final String UPLOAD_DIR = "uploads/";
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "请选择文件";
}
try {
// 创建上传目录
Path dirPath = Paths.get(UPLOAD_DIR);
if (!Files.exists(dirPath)) {
Files.createDirectories(dirPath);
}
// 保存文件
byte[] bytes = file.getBytes();
Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
Files.write(filePath, bytes);
return "文件上传成功: " + file.getOriginalFilename();
} catch (IOException e) {
return "上传失败: " + e.getMessage();
}
}
}文件下载通过返回Resource和设置响应头,让浏览器触发下载动作。
实现要点:
Controller 示例代码:
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
try {
// 构建文件路径
Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
} catch (MalformedURLException e) {
return ResponseEntity.badRequest().build();
}
}可用以下HTML测试上传功能:
```html 下载 test.pdf ```基本上就这些。只要配置好路径和权限,上传下载就能正常运行。注意生产环境要加文件类型校验、防重命名、权限控制等安全措施。不复杂但容易忽略细节。
以上就是如何在Java中实现文件上传下载功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号