springboot实现文件的上传下载
Spring Boot提供了简单易用的方式来处理文件上传和下载功能。下面是一个简单的示例:
创建一个文件上传的控制器
@RestController
public class FileUploadController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 保存文件
byte[] bytes = file.getBytes();
Path path = Paths.get(file.getOriginalFilename());
Files.write(path, bytes);
logger.info("文件上传成功:" + file.getOriginalFilename());
return "文件上传成功:" + file.getOriginalFilename();
} catch (IOException e) {
logger.error("文件上传失败:" + e.getMessage());
return "文件上传失败:" + e.getMessage();
}
}
}
创建文件下载的控制器
@RestController
public class FileDownloadController {
private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class);
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
try {
// 加载文件资源
Resource resource = new UrlResource("file:test.txt");
String filename = resource.getFilename();
String contentType = Files.probeContentType(Paths.get(filename));
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.body(resource);
} catch (IOException e) {
logger.error("文件下载失败:" + e.getMessage());
return ResponseEntity.notFound().build();
}
}
}
在应用程序中配置文件上传和下载的细节。
#文件上传配置
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.file-size-threshold=0
@Configuration
public class AppConfig implements WebMvcConfigurer {
//文件上传配置
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
resolver.setMaxUploadSize(10485760);
resolver.setMaxInMemorySize(4096);
return resolver;
}
//文件下载配置
@Bean
public ByteArrayResource byteArrayResource() {
return new ByteArrayResource(new byte[0]);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**")
.addResourceLocations("file:/usr/local/data/");
}
}
在页面上传文件
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传文件</button>
</form>
在页面下载文件
<a th:href="@{/download}" download="test.txt">下载文件</a>
这样就实现了文件上传和下载功能。当用户上传文件时,文件将被保存在应用程序的根目录中。当用户下载文件时,文件将从文件系统中加载并作为响应传输。
参考文章:http://blog.ncmem.com/wordpress/2023/12/05/springboot%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd-3/
欢迎入群一起讨论