简体   繁体   English

如何在classpath之外加载资源?

[英]How to load resources outside of classpath?

I'm using spring framework in webapplication and I would like to load resources (*.jpeg) stored outside of classpath. 我在webapplication中使用spring框架,我想加载存储在classpath外部的资源(* .jpeg)。

I'm calling GET method of some controller. 我正在调用一些控制器的GET方法。 It works when I call the photo from classpath. 当我从类路径调用照片时它可以工作。 But when I call paths like: /ext/media/photos/photo.png , file:/ext/media/photos/photo.png , /home/user/ext/media/photos/photo.png , http://some-web-image , it doesn't work. 但是,当我打电话喜欢的路径: /ext/media/photos/photo.pngfile:/ext/media/photos/photo.png/home/user/ext/media/photos/photo.pnghttp://some-web-image ,它不起作用。

@RequestMapping(value = "/loadPhoto", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<byte[]> loadPhoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/ext/media/photos/photo.png");
    return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), HttpStatus.CREATED);
}

I tried to map url to real location in spring context 我试图在春季环境中将网址映射到真实位置

<mvc:resources mapping="/ext/media/photos/**" location="file:/home/user/ext/media/photos/"/>

But I still can't get the resource. 但我仍然无法获得资源。 Is this right way how to get resource outside of classpath? 这是如何在classpath之外获取资源的正确方法吗?

You can use a FileSystemResource . 您可以使用FileSystemResource You don't need to return a byte[] . 您不需要返回byte[] Spring has a converter for producing the byte[] itself. Spring有一个用于生成byte[]本身的转换器。

@RequestMapping(value = "/loadPhoto", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<FileSystemResource> loadPhoto() throws IOException {
    FileSystemResource res = new FileSystemResource("/ext/media/photos/photo.png");
    return new ResponseEntity<FileSystemResource>(res, HttpStatus.CREATED);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM