java Spring从磁盘上的外部文件夹中获取文件和图像,在webapps之外?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34052259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:25:03  来源:igfitidea点击:

Spring get files and images from external folder on disk, outside webapps?

javaspringresourcesexternal

提问by Edgar

I have webproject which has images inside src/main/webapp folder. I would like to place images in different folder on the disk. But I have no idea how to manage requests to reach this images. Should I create some kind of httpServletlike shown here: http://balusc.omnifaces.org/2007/07/fileservlet.html

我有 webproject,它在 src/main/webapp 文件夹中有图像。我想将图像放在磁盘上的不同文件夹中。但我不知道如何管理访问这些图像的请求。我应该创建一些httpServlet像这里显示的东西:http: //balusc.omnifaces.org/2007/07/fileservlet.html

Or as I use Spring MVC with java configuration, there is more suitable and simpler way.

或者当我使用带有java配置的Spring MVC时,有更合适和更简单的方法。

Looking forward for your suggestions.

期待您的建议。

回答by Ralph

Use the spring mvc support for static resources, its locationattribute is an Spring Resource, so you could use file:prefix

对静态资源使用 spring mvc 支持,它的location属性是一个 Spring Resource,所以你可以使用file:前缀

<resources mapping="/resources/**" location="file:/my/external/directory/" />

or

或者

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("file:/my/external/directory/");
    }
}

@See Spring Reference Chapter 6.4 The ResourceLoaderfor a table that list all prefixed for resources

@See Spring Reference Chapter 6.4 The ResourceLoader用于列出所有资源前缀的表

回答by Mr. Mak

In my case I placed js and css resources in webapp and images in e://images/. For this case I use two mvc:resourcesmapping

就我而言,我将 js 和 css 资源放在 webapp 中,将图像放在e://images/. 对于这种情况,我使用两个mvc:resources映射

<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:resources mapping="/images/**" location="file:e://images/"/>

And locate the image of e: > images > abc.jpgusing ....

并使用 ...定位到e: > images > abc.jpg的图像。

<img src="../images/abc.jpg"/>

You could try also <img src="/images/abc.jpg"/> or <img src="images/abc.jpg">(If not work)

你也可以试试<img src="/images/abc.jpg"/> or <img src="images/abc.jpg">(如果不行)

The css/js linked under webapp > resources > js > xyz.jslike below.

webapp > resources > js > xyz.js下链接的 css/js如下所示。

<script type='text/javascript' src='../resources/js/xyz.js'></script>