@RestController
public class FileController {
@GetMapping("/files/{filename:.+}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
// 获取文件资源
Resource file = new FileSystemResource("/path/to/files/" + filename);
// 检查文件是否存在
if (!file.exists()) {
return ResponseEntity.notFound().build();
}
// 设置 Content-Type
String contentType = null;
try {
contentType = Files.probeContentType(Paths.get(file.getFile().getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
// 返回响应
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.body(file);
}
}
在上面的代码中,@GetMapping("/files/{filename:.+}") 注解指定了接口的 URL,其中 {filename:.+} 表示接受一个带有扩展名的文件名作为参数。
getFile() 方法使用 FileSystemResource 类来获取文件资源。如果文件不存在,则返回 404 错误响应;否则,使用 ResponseEntity 对象来设置响应头和响应体,将文件内容返回给客户端。
注意,上面的示例中使用的是文件系统路径。如果你想要从类路径中读取文件,可以使用 ClassPathResource 类来获取资源。例如,使用 new ClassPathResource("static/" + filename) 获取类路径中的静态文件。
同时,为了安全起见,你可能需要对文件路径进行一些校验,例如检查是否包含敏感字符,或限制访问的目录。