1、在SpringBoot里上传图片后返回了绝对路径,发现本地读取的环节上面出现了错误(Not allowed to load local resource),一开始用的是直接本地路径。

但是在页面上调试的出现了下面的错误,他的路径还是相对路径,那么解决这个问题,我们可以用虚拟路径,这篇文章就是说SpringBoot如何配置虚拟路径来解决这个问题。

coding++:解决Not allowed to load local resource错误-SpringBoot配置虚拟路径

我们只要添加一个配置文件就行:

package com.editors.kindeditor.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebAppConfiguration extends WebMvcConfigurerAdapter {
    /**
     * 添加一些虚拟路径的映射
     * 静态资源路径和上传文件的路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * @Description: 对文件的路径进行配置, 创建一个虚拟路径/Path/** ,即只要在< img src="/Path/picName.jpg" />便可以直接引用图片
         *这是图片的物理路径  "file:/+本地图片的地址"
         */
        registry.addResourceHandler("/Path/**").addResourceLocations("file:/C:/Users/lenovo/AppData/Local/Temp/tomcat-docbase.2975979620477460781.8080/upload/");
        super.addResourceHandlers(registry);
    }
}

其实这也是springMVC中的基本配置的静态资源映射,其中addResourceHandler指的是对外暴露的路径,而addResourceLocations是文件真正放的位置,如:你在src/main/resources下建立assets/js目录可以这样写:

registry.addResourceHandler("/Path/**").addResourceLocations("classpath:/assets");

 

相关文章:

  • 2021-10-31
  • 2021-04-19
  • 2021-07-06
  • 2021-07-21
  • 2021-07-07
  • 2021-06-14
  • 2021-11-06
  • 2021-09-28
猜你喜欢
  • 2021-07-10
  • 2021-08-12
  • 2021-07-30
  • 2021-08-07
  • 2021-05-25
相关资源
相似解决方案