在配置文件中加入文件路径配置
file.doc-dir=/usr/local/787k/doc/
fileconfig文件
@Data
@Configuration
public class FileConfig {
@Value("${file.doc-dir}")
private String docDir;
}
file的实现层
@Service
@Slf4j
public class FileService {
private final Path filePath;
public FileService(FileConfig fileConfig) {
filePath = Paths.get(fileConfig.getDocDir()).toAbsolutePath().normalize();
}
public Resource loadFileAsResource(String fileName) {
Path path = filePath.resolve(fileName).normalize();
try {
UrlResource resource = new UrlResource(path.toUri());
boolean exists = resource.exists();
if (exists) {
return resource;
}
throw new FileException("file " + fileName + " not found");
} catch (MalformedURLException e) {
throw new FileException("file " + fileName + " not found", e);
}
}
}
file控制层
@GetMapping("download/{fileName}")
public ResponseEntity<Resource> downloadFile(
@PathVariable String fileName, HttpServletRequest request) {
Resource resource = fileService.loadFileAsResource(fileName);
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException e) {
log.error("无法获取文件类型", e);
}
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(
HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename() + "")
.body(resource);
}
html页面
<p>个人简历:<a download href="/download/简历.doc" rel="external nofollow"
style="font-size: 16px;color: #fd971f;">下载我的简历</a></p>