简体   繁体   中英

Serving static content from Jersey resource method in a Spring Boot app

I'm using a combination of Spring Boot and JAX-RS for my REST API. In my Spring Java Application I have an image located in my resources directory. I want to serve this picture with an URL, it should be something like this:

localhost:8080/api/get/img/1/imageFileName.png

Like this I should be able to use this URL in my Angular Frontend Application in an img tag:

<img src="localhost:8080/api/get/img/1/imageFileName.png"/>

So the issue is, that I really want to have this stuff in my FileSystem. I definately do not want to return a byte array, but that's the only thing I could find so far. This is the only code I could come up with so far:

@GET
@Path("get/img/1")
public String getFile() {
    File file = Paths.get(".", "resources", "Mockup9EventsPageAsMember.png").normalize().toFile();
    return file.toString();
}

Obviously this will only return the path to the respective directory and not an URL link which I could use in my img tag.

Any suggestions how I can tell my SpringBoot JAX-RS Application to create an URL for me?

I could give you a solution to what you are trying to do, but it is definitely not recommended. The main reason would be the lack of caching. You would need to implement that yourself, which is already provided by the server if you let it serve all the static content.

In a Spring Boot + Jersey app, to be able to serve static content, you need to have the spring-boot-starter-web dependency. Then after that you can put all your static resources into src/main/resources/static 1 . If you put a file /images/foobar.png in that directory, then you can access it via localost:8080/images/foobar.png .

If you really really want to serve the static content from the resource method (which again I strongly recommend against), you don't have to return a byte[] . You could just return a File or an InputStream . Or you can use StreamingOutput (just search for some examples - you shouldn't have any problems finding any). But again, with this method, you need to take care of sending all the correct caching headers, or else the browser will not cache the files and they will served each time they are requested, which just uses unnecessary resources.


See also

  • If you have problems accessing the static content, it might be related to this issue

1. There are also more locations. See the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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