写一个文件下载的controller,service
时间: 2023-08-11 17:04:59 浏览: 101
下面是一个简单的文件下载的controller和service的示例代码,使用Spring框架和Java语言编写:
Controller:
```java
@RestController
public class FileDownloadController {
@Autowired
private FileDownloadService fileDownloadService;
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) {
Resource file = fileDownloadService.downloadFile(filename);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
}
```
Service:
```java
@Service
public class FileDownloadServiceImpl implements FileDownloadService {
@Value("${file.upload-dir}")
private String uploadDir;
@Override
public Resource downloadFile(String filename) {
Path file = Paths.get(uploadDir).resolve(filename);
Resource resource;
try {
resource = new UrlResource(file.toUri());
} catch (MalformedURLException e) {
throw new RuntimeException("Error: " + e.getMessage());
}
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("File not found: " + filename);
}
}
}
```
其中,`FileDownloadController`处理HTTP请求,并调用`FileDownloadService`提供的下载文件功能。`FileDownloadService`实现了下载文件的具体逻辑,包括查找文件,创建`Resource`对象并返回。在示例代码中,上传文件存储在`uploadDir`指定的目录下,具体目录路径在配置文件中进行配置。
阅读全文