gpt4 book ai didi

java - 当文件不存在时,Spring Boot使用InputStreamResource下载文件

转载 作者:行者123 更新时间:2023-12-02 01:51:13 27 4
gpt4 key购买 nike

我有一种使用 Spring Boot 使用 InputStreamResource 对象下载文件的工作方法。

有时我会遇到要下载的文件不存在的情况,在这种情况下,当文件下载结束时,我会得到其中写入的所有java异常

我的问题是在这种情况下如何继续拒绝用户文件下载,并得到“文件不存在”的响应?

我想过抛出异常,但用户在不检查日志的情况下无法获取信息

代码如下:

@GetMapping("/downloadfile")
public ResponseEntity<InputStreamResource> getFile(@RequestParam(value = "filePath") String filePath) throws FileNotFoundException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

File file = new File(filePath);
if (!file.exists()) {
// What should I do there?
//throw new CustomizeException("Could not find the file"); ?
}
MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, file);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(mediaType).contentLength(file.length()).body(resource);
}

最佳答案

您可以返回 404(未找到)。

    if (!file.exists()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

您不需要检查日志或抛出异常,因为已经处于通话状态

关于java - 当文件不存在时,Spring Boot使用InputStreamResource下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52968734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com