Spring boot文件路径映射配置代码实例
springboot配置本地资源映射路径需要配置一下映射资源位置,下面来介绍一下过程。
1.添加配置类
packageorg.jcut.tools;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.stereotype.Component;
importorg.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
publicclassMvcConfingimplementsWebMvcConfigurer{
@Value("${imgpath}")
Stringpath;
@Override
publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){
//当请求服务器中带有/imgs/的时候就是到指定路径中找出对应名字对应图片,其中**就代表匹配多层路径下的名字
registry.addResourceHandler("/imgs/**").addResourceLocations("file:"+path);
}
}
2.图片上传代码
//添加展示图片
Stringt_img=UUID.randomUUID().toString();//商品展示图片id
booleanflag=false;
for(MultipartFileff:file1){
StringtImgId=UUID.randomUUID().toString();
//写入图片名字的时候最好把获取图片映射名称写进去,方便获取图片
timg.insert(newTImg(tImgId,t_img,"imgs/"+tImgId+".jpg"));
try{
ff.transferTo(newFile(path+tImgId+".jpg"));
flag=true;
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。