1、主方法
@GetMapping(value = "/download/complaintTapeFile")
@Operation(summary = "下载工单音频文件", description = "根据工单音频文件id下载工单音频文件")
@TimedOperation(summary = "根据工单音频文件id下载工单音频文件", description = "根据工单音频文件id下载工单音频文件")
public ResponseEntity<byte[]> downloadComplaintTapeFile(
@Parameter(required = true, description = "工单音频文件id", allowEmptyValue = false, allowReserved = true) @RequestParam(value = "complaintTapeId") String complaintTapeId)
throws ControllerException {
if (StringUtils.isEmpty(complaintTapeId)) {
throw new ControllerException("id不可为空!");
}
try {
// 根据工单音频文件id下载工单音频文件
ComplaintTapeEntity complaintTapeEntity = complaintTapeService
.findComplaintTapById(complaintTapeId);
byte[] bytes = FileHandleHelper.downloadFile(complaintTapeEntity.getTapeFile());
// 设置响应头
HttpHeaders headers = FileHandleHelper.handleTapeFileHeader(complaintTapeEntity.getTapeFile());
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(bytes);
} catch (Exception e) {
String errorMessage = "下载失败:" + e.getMessage();
log.error(errorMessage, e);
throw new ControllerException(errorMessage);
}
}
2、查询文件存放位置
public ComplaintTapeEntity findComplaintTapById(String complaintTapeId) throws ServiceException {
Optional<ComplaintTapeEntity> complaintTapeEntityOptional = iComplaintTapeRepository.findById(complaintTapeId);
if (!complaintTapeEntityOptional.isPresent()) {
throw new ServiceException("工单录音文件不存在");
}
return complaintTapeEntityOptional.get();
}
3、将文件转为二进制流
public static byte[] downloadFile(String filePath) throws ServiceException {
Path fullPath = Paths.get(userPath, filePath);
if (!Files.exists(fullPath)) {
throw new ServiceException("文件不存在!");
}
File file = fullPath.toFile();
// 预分配字节数组,避免文件过大导致内存溢出
byte[] bytes = new byte[(int) file.length()];
try (InputStream inputStream = new FileInputStream(file)) {
inputStream.read(bytes);
return bytes;
} catch (IOException e) {
throw new ServiceException(e.getMessage(), e);
}
}
4、设置响应头
public static HttpHeaders handleTapeFileHeader(String filePath) throws ServiceException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("audio/wav"));
try {
Path fullPath = Paths.get(userPath, filePath);
String fileName = URLEncoder.encode(fullPath.getFileName().toString(),
StandardCharsets.UTF_8.toString());
headers.setContentDispositionFormData("attachment", fileName);
return headers;
} catch (UnsupportedEncodingException e) {
throw new ServiceException(e.getMessage(), e);
}
}