JBD
JBD

Reputation: 731

How to "display" files from external folder with spring boot 2.1.1

I'm learning spring boot vs 2.1.1

I would like to display in the template image from an external folder.

There is the app structure in tomcat 9:

|-webApp/ws-app     // where ws-app is the running app
|
|-webData           // where I would like to get the image to display in template

I've read many article from 5 years ago and I've tried to used them without success. Like this one: link

I've tried to add in application.properties this code:

spring.resources.static-locations=file:///C:/TMP/webData/images

Access it from the template like this:

http://localhost:8100/ws-app/img.jpg

I get 404 error

I've tried this coding too by creating a class like this :

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;


@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class CustomWebMvcAutoConfig implements WebMvcConfigurer {

    String myExternalFilePath = "file:///C:/TMP/webData/images";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(myExternalFilePath);
    }
}

The same error 404

Someone can help me to understand what I'm doing wrong or give me the correct way if what I'm trying to do is obsolete ?

Thanks so much

Upvotes: 0

Views: 4343

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

you should end your external-file-path with a /

you do not need to add @AutoConfigureAfter(DispatcherServletAutoConfiguration.class)

use http://localhost:8100/ws-app/images/img.jpg to access image if your image is stored as C:/TMP/webData/images/img.jpg

@Configuration
public class CustomWebMvcAutoConfig implements WebMvcConfigurer {

    String myExternalFilePath = "file:C:/TMP/webData/images/"; // end your path with a /

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(myExternalFilePath);
    }
}

Upvotes: 3

Related Questions