且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring Boot映像上传和服务

更新时间:2023-02-26 21:39:25

默认情况下,您的Spring Boot应用程序提供

Per default your Spring Boot application serves static content - in your case images - found at following locations:

  • /静态
  • /public
  • /资源
  • /META-INF/resources

因此通常,static/images/可能是Thymeleaf应该期望必须交付用于渲染的 static 图像的地方.但是,由于该位置是关于静态内容的,并且通常来说,将上传的(动态)内容保存在应用程序中是个坏主意,因此我建议不要这样做 .您是否考虑过将应用程序重新部署或移动到另一台计算机上会发生什么情况?您将不得不以繁琐的方式备份/移动图像.有更好的解决方案,将上载内容存储在应用程序之外的单独位置(例如,可以配置,并且可以由多个实例重用),甚至可以使用数据库来存储图像数据.这样还可以在事务性上下文中(例如,隔离和回滚)处理图像.

So usually, static/images/ would perhaps be the place where Thymeleaf should expect the static images which have to be delivered for rendering. But since this place is about static content and since it is in general a bad idea to save uploaded (dynamic) content inside your application I would recommend to DON'T do that. Did you think about what happens if your application is redeployed or moved to another machine? Your would have to backup / move the images in a cumbersome way. There are better solutions, storing the upload content at a separate location outside your app (which could for example be configurable and also reused by multiple instances) or even use a database to store image data. That would also enable handling images in a transactional context (e.g. isolation & rollbacks).

但是,如果您现在仍然希望将其存储在应用程序中,则可以通过添加搜索位置(实际上是 static 内容)来扩展位置.尽管Ajit的答案甚至文档仍然提供扩展自己的WebMvcConfigurerAdapter的建议,但我个人还是倾向于实现

But If you now want to still store it inside your app, your can extend the locations by adding places to search for (actually static content). Although the answer of Ajit and even the documentation still gives the advice to extend your own WebMvcConfigurerAdapter, I personally would tend to implement WebMvcConfigurer instead, because the former is deprecated.

在这种情况下,它应该看起来像:

In this case it should look like:

@Configuration
public class AdditionalResourceWebConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:images/");
    }
}