Springboot+Thymeleaf页面打开本地文件404问题

1、问题描述

(1)、首先,我在做文件上传时,存放到项目的src下面,但是在网站上打开页面加载文件时报404错误,后来发现是文件没有同步到target文件夹里面,我便将文件上传路径写到target文件夹里面,
虽然在idea中跑项目没有问题,但是经过打包部署到服务器上,运行后又报404错误,气的脑壳疼。

2、解决方法

(1)、配置虚拟目录
a、在yml文件中写上

prop:
  upload-folder: D:/file/

spring:
	 resources:
      static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${prop.upload-folde}

b、创建个映射类(拦截)

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

/**
 * 图片绝对地址与虚拟地址映射
 */

@Configuration
public class FileConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //文件磁盘图片路径 映射
        //handler为前台访问的目录,locations为files相对应的本地路径
        registry.addResourceHandler("/upload/**").addResourceLocations("file:/D:/file/upload/");
    }
}

PS:
例子:

<img src="/upload/images/Handsome.jpg">

猜你喜欢

转载自blog.csdn.net/G_liunian/article/details/105598695