首页 > 解决方案 > Spring Boot:文件下载在项目根文件夹内创建一个新文件

问题描述

我正在Spring boot 2.2.6.RELEASE使用Java 11. 我在静态文件夹中有一些图像。示例:static/img/category/some_image.jpg

当我单击 GUI 上的下载按钮时,此方法在后端运行。

@ResponseBody
@GetMapping(value = "/download", produces = MediaType.IMAGE_JPEG_VALUE)
public FileSystemResource downloadImage(@Param(value = "url") String url,
                                        @Param(value = "id") Integer id,
                                        HttpServletResponse response) throws IOException {

    Media media = mediaService.findById(id);
    String fileName = media.getFileName();

    InputStream inputStream = new ClassPathResource(url).getInputStream();
    File file = new File(fileName);
    FileUtils.copyToFile(inputStream, file);
    inputStream.close();

    response.addHeader("Content-Disposition", "attachment; filename=" + fileName + ".jpg");
    return new FileSystemResource(file);
}

我正在使用InputStream,因为我将在 docker 容器中将这个应用程序作为 jar 文件运行。无论如何,这种方法可以正常工作,并且可以正常下载图像。但问题是,文件下载完成后,jpg会在项目根目录下新建一个不带扩展名( )的文件。它的内容是这样的:

ffd8 ffe1 0018 4578 6966 0000 4949 2a00
0800 0000 0000 0000 0000 0000 ffec 0011
4475 636b 7900 0100 0400 0000 3c00 00ff
ee00 0e41 646f 6265 0064 c000 0000 01ff
db00 8400 0604 0404 0504 0605 0506 0906
0506 090b 0806 0608 0b0c 0a0a 0b0a 0a0c
100c 0c0c 0c0c 0c10 0c0e 0f10 0f0e 0c13
...

如果我重命名文件并添加文件 jpg 扩展名,则图像将正常打开。对于每个下载的文件,都会在项目根文件夹中创建一个新文件,这并不好。知道为什么会这样吗?

标签: springspring-boot

解决方案


这是因为File file = new File(fileName);实际上是在类路径上创建一个永久文件。

需要做的是创建一个临时文件

替换File file = new File(fileName);File file = File.createTempFile(fileName, "jpeg");

所以,整个方法应该是这样的

@ResponseBody
@GetMapping(value = "/download", produces = MediaType.IMAGE_JPEG_VALUE)
public FileSystemResource downloadImage(@Param(value = "url") String url,
                                        @Param(value = "id") Integer id,
                                        HttpServletResponse response) throws IOException {

    Media media = mediaService.findById(id);
    String fileName = media.getFileName();

    InputStream inputStream = new ClassPathResource(url).getInputStream();
    File file = File.createTempFile(fileName,"");
    FileUtils.copyToFile(inputStream, file);
    inputStream.close();
    file.deleteOnExit(); // delete temp file on exit
    response.addHeader("Content-Disposition", "attachment; filename=" + fileName + ".jpg");
    return new FileSystemResource(file);
}

推荐阅读