从资源文件夹读取图像

时间:2020-04-10 18:06:05

标签: java

我想从资源文件夹中读取图像并将其作为响应正文发送。我尝试过:

@RequestMapping(value = "/image/{imageid}",method= RequestMethod.GET,produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImageWithMediaType(@PathVariable int imageid) throws IOException {

        File file = new File(String.valueOf(getClass().getResource("/resources/color.jpg")));
        byte[] fileContent = Files.readAllBytes(file.toPath());

        InputStream in = new ByteArrayInputStream(fileContent);
        return IOUtils.toByteArray(in);
    }

但是我得到:threw exception java.nio.file.NoSuchFileException: null at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)

文件color.jpg位于此处,但由于某种原因未找到。你知道我该如何解决这个问题?

Directory of C:\Users\........war_file\src\main\resources

10/04/2020  20:58    <DIR>          .
10/04/2020  20:58    <DIR>          ..
10/04/2020  20:05               816 application-dev.yml
10/04/2020  19:26               816 application-local.yml
10/04/2020  20:05               813 application.yml
10/04/2020  20:58           187,405 color.jpg
11/03/2020  01:43               795 logback-spring.xml
               5 File(s)        190,645 bytes
               2 Dir(s)  48,421,285,888 bytes free

编辑:解决方案:

@RequestMapping(value = "/image/{imageid}",method= RequestMethod.GET,produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImageWithMediaType(@PathVariable int imageid) throws IOException {

        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("color.jpg");
        byte[] bytes = IOUtils.toByteArray(is);
        InputStream in = new ByteArrayInputStream(bytes);
        return IOUtils.toByteArray(in);
    }

3 个答案:

答案 0 :(得分:0)

getClass().getResource("/resources/color.jpg"))

仅尝试不带“ / resources”(getClass().getResource("color.jpg")))的“ color.jpg”。因为您已经获得资源。另外,请确保已设置资源文件夹。

答案 1 :(得分:0)

假设这是一个Spring启动项目,则可以从以下资源访问任何文件

File file = new File(getClass().getResource("color.jpg").getFile()); //Remove "resources" 

答案 2 :(得分:0)

这适用于Spring Boot 2.2.6.RELEASE。

@Controller
public class Test {

    @Autowired
    private ResourceLoader resourceLoader;

    @RequestMapping(value = "/image/{imageid}", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody
    byte[] getImageWithMediaType(@PathVariable int imageid) throws IOException {

        Resource resource = resourceLoader.getResource("classpath:color.jpg");
        File file = resource.getFile();
        byte[] fileContent = Files.readAllBytes(file.toPath());

        InputStream in = new ByteArrayInputStream(fileContent);
        return IOUtils.toByteArray(in);
    }
}
相关问题