使用Spring Boot实现文件上传下载:通过MultipartFile接收文件并保存,配置存储路径,记录元数据;2. 下载时通过HttpServletResponse输出文件流,设置响应头触发下载;3. 前端使用form表单上传,a标签下载;4. 建议限制文件类型与大小,防覆盖重命名,校验路径安全。

实现课程资源的上传与下载功能,核心是通过Java后端处理文件的接收与响应,结合前端表单完成交互。以下是基于Spring Boot框架的实用实现方式。
使用Spring MVC接收前端上传的文件,保存到服务器指定目录。
关键步骤:
示例代码:
立即学习“Java免费学习笔记(深入)”;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file,
@RequestParam("courseId") Long courseId) {
if (file.isEmpty()) {
return "上传失败:文件为空";
}
try {
String uploadDir = "D:/course_resources/" + courseId + "/";
File dir = new File(uploadDir);
if (!dir.exists()) dir.mkdirs();
<pre class='brush:java;toolbar:false;'> String filePath = uploadDir + file.getOriginalFilename();
file.transferTo(new File(filePath));
// 可选:将文件信息存入数据库
resourceService.saveResource(courseId, file.getOriginalFilename(), filePath);
return "文件上传成功";
} catch (IOException e) {
return "上传失败:" + e.getMessage();
}}
通过HttpServletResponse输出文件流,触发浏览器下载。
实现要点:
示例代码:
立即学习“Java免费学习笔记(深入)”;
@GetMapping("/download/{fileName}")
public void downloadFile(@PathVariable String fileName,
HttpServletResponse response) throws IOException {
String filePath = "D:/course_resources/1001/" + fileName;
File file = new File(filePath);
<pre class='brush:java;toolbar:false;'>if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" +
java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");
FileInputStream fis = new FileInputStream(file);
response.getOutputStream().write(fis.readAllBytes());
fis.close();
} else {
response.setStatus(404);
response.getWriter().write("文件未找到");
}}
提供简单HTML页面用于测试上传和下载。
<!-- 上传表单 --> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" required> <input type="number" name="courseId" value="1001" hidden> <button type="submit">上传资源</button> </form> <p><!-- 下载链接 --> <a href="/download/Java教程.pdf">下载Java教程</a></p>
实际应用中需考虑以下问题:
基本上就这些。用Spring Boot加原生IO操作,能快速搭建稳定可用的文件服务。注意路径配置和异常处理,基本不会出问题。
以上就是如何使用Java实现课程资源上传与下载的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号