用sprint boot写一个实现文件上传下载功能的代码
时间: 2024-06-11 20:06:36 浏览: 152
这里是一个使用Spring Boot实现文件上传下载功能的示例代码,包含了上传和下载文件的功能:
1. 首先,需要在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
```
2. 创建一个控制器类,用于处理文件上传和下载的请求:
```
@RestController
public class FileController {
private static final String UPLOAD_DIR = "uploads";
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("Please select a file to upload");
}
try {
Path uploadPath = Paths.get(UPLOAD_DIR);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
Path filePath = uploadPath.resolve(file.getOriginalFilename());
Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok().body("File uploaded successfully: " + file.getOriginalFilename());
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file: " + e.getMessage());
}
}
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> handleFileDownload(@PathVariable String fileName) {
Resource resource = new FileSystemResource(UPLOAD_DIR + "/" + fileName);
if (resource.exists()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
}
```
3. 创建一个HTML页面,用于上传文件:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<div>
<input type="file" name="file" required>
</div>
<div>
<input type="submit" value="Upload">
</div>
</form>
</body>
</html>
```
4. 创建另一个HTML页面,用于下载文件:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Download</title>
</head>
<body>
<h1>File Download</h1>
<form method="get" action="/download">
<div>
<input type="text" name="fileName" required>
</div>
<div>
<input type="submit" value="Download">
</div>
</form>
</body>
</html>
```
5. 在应用程序的主类中添加以下代码,以启用静态资源处理和Thymeleaf模板引擎:
```
@SpringBootApplication
public class FileUploadDownloadApplication {
public static void main(String[] args) {
SpringApplication.run(FileUploadDownloadApplication.class, args);
}
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploads/**").addResourceLocations("file:uploads/");
}
};
}
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.setEnableSpringELCompiler(true);
return engine;
}
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
}
```
这样,就可以使用Spring Boot来实现文件上传下载功能了。上传文件后,会将文件保存在应用程序运行目录下的uploads文件夹中,然后可以通过访问/download/{fileName}的URL来下载文件。
阅读全文