springboot文件上传-springsecurity白名单-资源虚拟路径映射

飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

分类: springboot 专栏: 在线教育项目实战 标签: springboot文件上传

2023-05-19 19:11:43 576浏览

springboot文件上传
  • 上传controller
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadFileController {

    @PostMapping("/avatar")
    public ResultDto uploadAvatar(MultipartFile file){
        SimpleDateFormat format= new SimpleDateFormat("yyyy/MM/dd");
        String filePath = format.format(new Date());
        try {
            File directory=new File("D://avatar/"+filePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            //文件名最好重命名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replace("-", "");
            File saveFile= new File("D://avatar/"+filePath+"/"+fileName+suffix);

            file.transferTo(saveFile);
            return ResultDto.success("上传成功","/avatar/"+filePath+"/"+fileName+suffix);
        } catch (IOException e) {
            e.printStackTrace();
            throw new JfException(50000,"头像上传失败");
        }

    }

}
  • 配置文件虚拟路径
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/avatar/**").addResourceLocations("file:D:/avatar/");
    }
}
  • springsecurity设置白名单
   public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/avatar/**",

好博客就要一起分享哦!分享海报

此处可发布评论

评论(2展开评论

蓝色妖姬 能力:10

2023-06-30 09:59:46

温习中
蓝色妖姬 能力:10

2023-05-23 08:00:01

学习中
点击查看更多评论

展开评论

您可能感兴趣的博客

客服QQ 1913284695