misco
misco

Reputation: 1952

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.

I'm calling GET method of some controller. 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.

@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?

Upvotes: 2

Views: 2726

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280175

You can use a FileSystemResource. You don't need to return a byte[]. Spring has a converter for producing the byte[] itself.

@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);
}

Upvotes: 5

Related Questions