spring文件上传下载
时间: 2023-10-28 14:48:19 浏览: 38
Spring提供了多种方式来实现文件上传和下载,以下是其中常用的两种方式:
1. 使用Spring MVC的MultipartFile实现文件上传和下载
MultipartFile是Spring MVC中用于处理文件上传的接口,它提供了多种方法来获取文件信息和操作文件内容。以下是示例代码:
@Controller
@RequestMapping("/file")
public class FileController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get("uploaded-files/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/";
}
@GetMapping("/download")
public ResponseEntity<Resource> serveFile(@RequestParam("filename") String filename) {
Resource file = new FileSystemResource("uploaded-files/" + filename);
if (file.exists()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
} else {
return ResponseEntity.notFound().build();
}
}
}
2. 使用Spring Boot的ResourceHandler实现静态资源访问和下载
Spring Boot提供了ResourceHandler来处理静态资源的访问和下载,可以通过配置指定静态资源的路径和URL映射。以下是示例代码:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("file:/path/to/uploaded-files/")
.setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
}
}
@Controller
public class FileController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) throws IOException {
Path filePath = Paths.get("/path/to/uploaded-files/" + filename);
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();
}
}
}
以上两种方式都可以实现文件上传和下载,选择哪种方式取决于具体情况和项目需求。