您好,登录后才能下订单哦!
在现代Web应用程序中,文件上传和下载是非常常见的功能。Spring MVC提供了强大的支持来实现这些功能,特别是在使用注解配置的情况下。本文将详细介绍如何使用Spring MVC的注解方式来实现文件上传和下载功能。
在开始之前,确保你已经配置好了Spring MVC的环境。以下是一些基本的依赖项:
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.21</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- Jackson for JSON support -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
</dependencies>
Spring MVC使用MultipartResolver
来处理文件上传。我们需要在Spring配置文件中配置CommonsMultipartResolver
。
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(10485760); // 10MB
resolver.setMaxInMemorySize(1048576); // 1MB
resolver.setDefaultEncoding("utf-8");
return resolver;
}
}
接下来,我们创建一个控制器来处理文件上传请求。
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件内容
byte[] bytes = file.getBytes();
// 保存文件到服务器
Path path = Paths.get("uploads/" + fileName);
Files.write(path, bytes);
model.addAttribute("message", "文件上传成功: " + fileName);
} catch (IOException e) {
e.printStackTrace();
model.addAttribute("message", "文件上传失败: " + e.getMessage());
}
} else {
model.addAttribute("message", "文件为空,请选择文件上传");
}
return "uploadResult";
}
}
在src/main/resources/templates
目录下创建一个upload.html
文件。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>文件上传</title>
</head>
<body>
<h1>文件上传</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
</body>
</html>
在src/main/resources/templates
目录下创建一个uploadResult.html
文件。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>上传结果</title>
</head>
<body>
<h1>上传结果</h1>
<p th:text="${message}"></p>
<a href="/upload">返回上传页面</a>
</body>
</html>
我们创建一个控制器来处理文件下载请求。
@Controller
public class FileDownloadController {
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
try {
Path path = Paths.get("uploads/" + fileName);
Resource resource = new UrlResource(path.toUri());
if (resource.exists() || resource.isReadable()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
throw new RuntimeException("文件不存在或不可读");
}
} catch (MalformedURLException e) {
throw new RuntimeException("文件路径错误", e);
}
}
}
在src/main/resources/templates
目录下创建一个download.html
文件。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>文件下载</title>
</head>
<body>
<h1>文件下载</h1>
<ul>
<li th:each="file : ${files}">
<a th:href="@{/download/{fileName}(fileName=${file})}" th:text="${file}"></a>
</li>
</ul>
</body>
</html>
我们还需要一个控制器来列出所有可下载的文件。
@Controller
public class FileListController {
@GetMapping("/files")
public String listFiles(Model model) {
try {
List<String> files = Files.list(Paths.get("uploads"))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toList());
model.addAttribute("files", files);
} catch (IOException e) {
e.printStackTrace();
}
return "download";
}
}
确保你的Spring Boot应用程序已经启动,并且可以通过浏览器访问。
http://localhost:8080/upload
。http://localhost:8080/files
。通过本文的介绍,你应该已经掌握了如何使用Spring MVC的注解方式来实现文件上传和下载功能。Spring MVC提供了强大的支持,使得这些功能的实现变得非常简单和灵活。希望本文对你有所帮助,祝你在开发过程中顺利实现文件上传和下载功能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。