springboot通过设置addResourceHandlers拦截请求访问本地资源

通过http请求服务资源     

    springboot有一个目录:static这个目录其实就是静态资源目录,这个目录下面的文件是可以通过http直接问题的。但是程序话一般打成jar包,我们没办法去文件写入到这个static下,所以springboot提供静态资源目录的额外的映射机制,就是静态资源服务映射。它就类似于:nginx的静态资源映射。

需要实现WebMvcConfigurer接口

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {


    @Value("${file.staticPatternPath}")
    private String staticPatternPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //registry.addResourceHandler("访问的路径").addResourceLocations("上传资源的路径");
        //注意: uploadFolder 后面一定跟/ 如 E:/test/  如果E:/test 就会出现404
       registry.addResourceHandler(staticPatternPath).addResourceLocations("file:"+uploadFolder);

    }
    
}

配置文件:

#注意每个访问路径后面的路径加 / 
file:
  uploadFolder: E:/test/
  staticPath: http://localhost:8888/
  staticPatternPath: /uploadFile/**

控制层:

  @RequestMapping("/upload/file")
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile multipartFile){
        if (multipartFile.isEmpty()){
            return "文件有误";
        }
        return uploadService.uploadFile(multipartFile); //application/x-msdownload

    }

service


    @Value("${file.uploadFolder}")
    private String uploadFolder;  //具体位置

    @Value("${file.staticPath}")
    private String staticPath;  //http://localhpst:8080
    

    /**
     *MultipartFile 这个对象是springmvc提供的文件上传的接受的类
     * 他的底层自动会和HttpServletRequest request 中的request.getInputStream融合
     * 从而达到文件上传的效果,也就是告诉我们一个道理
     * 文件上传的底层原理request.getInputStream
     * @param multipartFile
     * @return
     */
    public String uploadFile(MultipartFile multipartFile){
        try {
            //文件名字
            String filename = multipartFile.getOriginalFilename();
            //文件后缀
            String suffix = filename.substring(filename.lastIndexOf("."));
            // 生成的唯一的文件名:能不能用中文名:不能因为统一用英文命名。
            String newFileName = UUID.randomUUID().toString() + suffix;

            //日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String format = dateFormat.format(new Date());//2021/11/03

            //指定文件上传的目录
            String targetPath = uploadFolder + format;
            File file = new File(targetPath);
            // 如果目录不存在 递归创建
            if (!file.exists())
                file.mkdirs();

            //指定文件上传以后的服务器的完整的文件名
            File targetFileName = new File(targetPath,newFileName);

            //文件上传到指定的目录
            multipartFile.transferTo(targetFileName);
            //可访问的路径要返回页面
            // http://localhpst:8888/uploadFile/2021/10/27/5f61dea2-4b77-4068-8d0b-fdf415eac6df.png
            //文件所在的目录和文件名(生成的)
            String filename1 = format + "/"+newFileName;
            return staticPath+"uploadFile/"+filename1;
        } catch (IOException e) {
            e.printStackTrace();
            return "faile";
        }

    }

文件上传成功返回一个结果

 下面两张图结合一起来看就可以得出结论。结论在图片中

以上内容属于个人笔记整理,如有错误,欢迎批评指正

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中设置拦截器时,需要注意一些细节。 首先,如果你的静态资源图片不显示,可能是因为拦截器配置不当导致的。在配置拦截器时,可以使用`addPathPatterns()`方法设置需要拦截的路径,同时也需要使用`excludePathPatterns()`方法排除不需要拦截的路径。如果没有正确地配置排除路径,就可能会导致静态资源无法访问。 另外,还需要在配置文件中设置静态资源路径。在Spring Boot中,默认情况下静态资源路径为`/static`、`/public`、`/resources`和`/META-INF/resources`。如果你的静态资源存储在其他路径下,需要在配置文件中进行设置。 以下是一个示例拦截器配置,可以参考一下: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new UserInterceptor()) .addPathPatterns("/user/**") .excludePathPatterns("/user/login", "/user/register"); registry.addInterceptor(new AdminInterceptor()) .addPathPatterns("/admin/**") .excludePathPatterns("/admin/login"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); } } ``` 在上面的示例中,`UserInterceptor`和`AdminInterceptor`分别是自定义的拦截器类。`addPathPatterns()`方法设置需要拦截的路径,`excludePathPatterns()`方法排除不需要拦截的路径。`addResourceHandlers()`方法设置静态资源路径为`/static/**`,存储在`classpath:/static/`下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值