简体   繁体   English

如何在 Java Spring Boot MVC 中提供静态和上传的内容

[英]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:我在 application.properties 中编写了以下代码:

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

where public is the directory of my static and uploaded content, like user profile and others.其中 public 是我的静态和上传内容的目录,如用户个人资料等。

but it's giving me a 404 error when I access the file like:但是当我访问文件时它给了我一个 404 错误,例如:

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:如果您在 application.properties 中设置了server.servlet.context-path (或 server.servlet.contextPath,它是相同的),则需要在 URL 中包含这部分,例如:

server.servlet.context-path=/foo server.servlet.context-path=/foo

then you should visit http://localhost:8082/foo/uploads/file/a.png那么你应该访问http://localhost:8082/foo/uploads/file/a.png

Unless you don't have other configuration parameters set, spring boot should serve static resources under /除非你没有设置其他配置参数,否则spring boot应该服务/下的静态资源

So if your static resources are under a folder called public/file you'll find that at the url localhost:8082/file/a.png因此,如果您的静态资源位于名为public/file夹下,您会在 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如果您有spring.mvc.static-path-pattern参数集 spring boot 应该在该路径上提供静态资源

In the case of spring.mvc.static-path-pattern = files (for example) it will serve them at http://localhost:8082/files/file/a.png在 spring.mvc.static-path-pattern = files(例如)的情况下,它将在http://localhost:8082/files/file/a.png

Here's a good article explaining all : https://www.baeldung.com/spring-mvc-static-resources这是一篇解释所有内容的好文章: https : //www.baeldung.com/spring-mvc-static-resources

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

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