简体   繁体   中英

How to serve static and uploaded content in Java Spring Boot MVC

I try with following process to serve static content but have no luck.

I have written the below code in my application.properties:

spring.resources.static-locations=classpath:/public/

where public is the directory of my static and uploaded content, like user profile and others.

but it's giving me a 404 error when I access the file like:

http://localhost:8082/public/uploads/file/a.png

I have also tried with:

http://localhost:8082/uploads/file/a.png

but it does not working either.

If you have server.servlet.context-path (or server.servlet.contextPath, it's the same) set in your application.properties, you need to have this part in the URL, for example:

server.servlet.context-path=/foo

then you should visit http://localhost:8082/foo/uploads/file/a.png

Unless you don't have other configuration parameters set, spring boot should serve static resources under /

So if your static resources are under a folder called public/file you'll find that at the url localhost:8082/file/a.png

If you have spring.mvc.static-path-pattern parameter set spring boot should serve static resources at that path

In the case of spring.mvc.static-path-pattern = files (for example) it will serve them at http://localhost:8082/files/file/a.png

Here's a good article explaining all : https://www.baeldung.com/spring-mvc-static-resources

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