问题出现的原因:想要在前端访问本地的图片,结果被浏览器拒绝了,浏览器会认为这是一种不安全的方式,所以给拒绝访问了,
环境描述 :springboot +thyemleaf前后端分离模式开发
我觉得将静态资源的路径引入 applocation配置文件里可以解决这个问题,但是那样改变了静态资源的路径,因为我当初的想法就是上传的图片不放入静态资源下,直接上传到本地目录下,所以才出现这个问题。
解决方案:
引入拦截器配置:
package com.config;
import com.incerceptor.LoginInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 通过@Bean注解,将我们定义的拦截器注册到Spring容器
*
* @return
*/
@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
/**
* 可以将不需要拦截的路径 ,比如说静态资源的路径放行,将下面的路劲添加到拦截器的后缀即可
*/
// 这里需要放行所有的静态资源
String[] excludePathPatterns = {
"/static/**",
"file:C:/Users/ly/IdeaProjects/Tyust_face/img/photo/"
};
/**
* 重写接口中的addInterceptors方法,添加自定义拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 通过registry来注册拦截器,通过addPathPatterns来添加拦截路径
registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/admin/**")
.addPathPatterns("/teacher/**").excludePathPatterns(excludePathPatterns);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**").addResourceLocations("file:///C:/Users/ly/IdeaProjects/Tyust_face/");
}
}
然后thyemleaf模板 :
<img th:src="@{'/image/'+${student.image}}" height="150px" width="100px">
这样就可以成功在前端访问到图片了。提一嘴,student image存放的是图片的相对路径,
也就是路径配置是file:///C:/Users/ly/IdeaProjects/Tyust_face/" + image的路径,写的时候要注意一下,我就是这里没注意才导致看了半天不知道哪里出错。