谢谢,计时、返回response,基本上差不多了。但是chatgpt提示我,另一种方法是如下修改:
CompletableFuture<ResponseEntity<Resource>> downloadFuture = CompletableFuture.supplyAsync(() -> {
// 获取文件长度
long fileSize = file.length();
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Length", String.valueOf(fileSize));
headers.add("Content-Disposition", "attachment; filename=" + 文件名);
// 创建文件资源对象
Resource resource = new FileSystemResource(file);
// 返回整个文件内容
ResponseEntity<Resource> responseEntity = null;
try {
responseEntity = ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(resource.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
// 其他 IO 异常情况,返回 500 响应和错误信息
String errorMsg = "Error occurred while reading the file";
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ByteArrayResource(errorMsg.getBytes()));
}
// long endTime1 = System.currentTimeMillis();
// long duration = endTime1 - startTime;
// System.out.println("allocateModelslices,下载文件,程序耗时:" + duration + " 毫秒");
// System.out.println(打印当前时间_精确到毫秒.打印时间到毫秒() + " " + sliceName + " 下载文件结束");
// 返回整个文件内容
return responseEntity;
});
// 下载完成后的回调函数
downloadFuture.thenAccept(responseEntity -> {
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("下载耗时: " + duration + "毫秒");
// 继续处理返回的responseEntity或将耗时信息返回给前端
});
return ResponseEntity.status(741258).body(new ByteArrayResource("not know".getBytes()));
但是我用了上面的代码后,后端能显示:
下载耗时: 12毫秒————也就是执行到了 回调函数 里,
但是前端没有下载到文件,前端显示: "not know"(也就是最后一个return)
这是怎么回事?为何这个代码,不能下载文件了?
【 在 CHNSTAR 的大作中提到: 】
: 你说的是在前端能接收到服务器返回的异常信息吗?
: 反正你已经拿到了HttpServletResponse对象了
: 在方法内加try-catch,补货异常后直接用HttpServletResponse向客户端输出异常信息就行了。
: ...................
--
FROM 120.242.238.*