zoukankan      html  css  js  c++  java
  • 【JavaWeb】SpringBoot配置静态资源路径

    springboot默认有三个静态资源路径,分别是classpath下的public、static和templas,它们特点如下:

    public:可以直接访问的。在浏览器中可以直接输入文件路径访问到的,不要经过controller。

    static:一半存放项目图片,csss及js文件等,不可以直接访问。访问时使用相对路径访问。比如static下有个js文件夹,里边有个a.js文件,则在项目中要引用这个文件时,只需要 /js/a.js,是不需要加static的,前边加个斜杠表示项目根路径。

    templates:存放html等视图页面,不能直接访问。访问时需要经过controller返回到视图页面。

    自定义静态资源路径

    以上三个路径是默认的,但是他们都是编译后放到class文件夹下边的,不利于程序和数据的分离。所以SpringBoot也支持自定义静态资源路径。

    例如我们要将上传的文件保存在硬盘的某个地方,在配置文件中这样写:

    //自定义路径
    web.file-path=C:/WebFile/xgpblogs/
    //用于静态资源的路径模式。
    spring.mvc.static-path-pattern=/**
    //配置路径
    spring.resources.static-locations=classpath:/META-INF/resources/,
      classpath:/resources/,
      classpath:/static/,
      classpath:/public/,
      file:${web.file-path}

    然后使用时:

    @Value("${web.file-path}")
    String filePath = ""
    

    这样就获取到了自定义的文件路径。

    上传文件时只需要filePath+fileName即可得到完整的文件路径。

    上传文件并保存

    在Controller中接收MultipartFile再调用saveOurPic即可。

    @ResponseBody
        @RequestMapping("uploadPic")
        public String uploadPic(@RequestParam("file")MultipartFile[] file) throws IOException {
            for(MultipartFile f : file){
                fileService.saveOurPic(f);
            }
            return "{"code":200}";
        }

    注意:在使用MultipartFile必须注明@RequestParam(“”)。

    //保存文件的代码
     @Value("${web.file-path}")
        private String fp ;
    public int saveOurPic(MultipartFile file) throws IOException {
            String filePath = fp+"/ourpic/";
            int oldNum = getFileNum(filePath);
            String fileName = (oldNum+1)+".jpg";
            File newFile = new File(filePath+fileName);//主要
            file.transferTo(newFile);//主要
            ReduceImg.reduceImg(filePath+fileName,filePath+fileName,0,0,0.2f);
            return oldNum+1;
        }
  • 相关阅读:
    阿里十八罗汉、腾讯五虎将、百度七剑客……大佬们是如何找到创始合伙人的?
    子元素margin-top后,跟父元素一起下沉
    css 学习网址
    文字折行不折行 css
    js typeof
    position_css
    springmvc initial初始化
    android MD5 SHA1
    hibernate 三种状态
    Springmvc Exception
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286724.html
Copyright © 2011-2022 走看看