Spring Boot images uploading and serving

前端 未结 3 1495
南方客
南方客 2020-12-30 10:22

I\'m making new Spring Boot app and want to be able to store and serve images, I want images to be stored in applications directory:

this is what uploading look

3条回答
  •  伪装坚强ぢ
    2020-12-30 11:02

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

    • /static
    • /public
    • /resources
    • /META-INF/resources

    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).

    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/");
        }
    }
    

提交回复
热议问题