首页 > 解决方案 > 在spring boot和vue js中显示资源文件夹中的图像

问题描述

我正在尝试构建一个将图像上传到具有目录的资源内的图像文件夹的功能:

资源/静态/图像/imagesName.jpg

下面是这个函数的代码:

public String Redirection(String Parameter, MultipartFile sourceFile, Integer VID) throws IOException, NoSuchAlgorithmException, KeyManagementException{

// upload image into resources

byte[] bytes = sourceFile.getBytes();
String fileType = sourceFile.getOriginalFilename();
String[] parts = fileType.split(Pattern.quote("."));
String part1 = parts[0]; 
String part2 = parts[1];

String fileLocation = new File("src\\main\\resources\\static\\images").getAbsolutePath() + "\\" + VID + "." + part2;
System.out.println(fileLocation);
Path path = Paths.get(fileLocation);
Files.write(path, bytes);
}

对于这部分,它工作正常。但是,当我尝试在 vue 上的前端检索图像时,我不知道它应该如何工作。我试图参考 Bamossza 回答的这个问题

Spring Boot 无法从资源文件夹中提供静态图像

我在我的主应用程序上添加配置如下:

@Configuration
public class WebConfig implements WebMvcConfigurer {      
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/static/")
        .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
    }
}

在 Vue.js 上的前端,我通过执行检索图像

<CImg src="/images/141.png" shape="rounded"></CImg>

图像应该是动态的,但现在,我只是想让它首先显示,但它没有显示任何内容。有什么解决方案可以让它工作吗?先感谢您!

标签: javaspring-bootvue.js

解决方案


推荐阅读