问题
有时候我们想通过浏览器直接访问电脑本地的图片,但是浏览器出于安全考虑不允许直接通过本地绝对路径去访问资源。所以我们需要在设备上起一个http服务,把路径设置为静态资源路径,这样,在页面上你就可以通过类似于http://localhost:8080/static/test.jpg的方式访问这个图片了
后端项目
步骤一
resource下新建文件夹static
步骤二
修改pon.xml,放行静态资源的访问
<resources>
<resource>
<directory>src/main/webapp</directory>
<filtering>false</filtering>
<includes>
<include>**/*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
步骤三
启动项目后浏览器访问(端口号根据你启动的java服务占用的端口号自行替换)
http://localhost:9090/test.jpg
如果仍然不能访问,请检查你是否在某个拦截器中拦截了静态资源的访问,举个例子
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static/**"); // 放行
}
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor();
}
}
前端项目
步骤一
public下新建文件夹,存入图片
步骤二
启动项目后浏览器访问(端口号自行更换)
http://localhost:8080/files/1c02f255b41c43f7ae823cec6550e2e7.jpg