zoukankan      html  css  js  c++  java
  • springboot之静态资源路径配置

    静态资源路径是指系统可以直接访问的路径,且路径下的所有文件均可被用户直接读取。

    在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/,从这里可以看出这里的静态资源路径都是在classpath中(也就是在项目路径下指定的这几个文件夹)

    试想这样一种情况:一个网站有文件上传文件的功能,如果被上传的文件放在上述的那些文件夹中会有怎样的后果?

    • 网站数据与程序代码不能有效分离;
    • 当项目被打包成一个.jar文件部署时,再将上传的文件放到这个.jar文件中是有多么低的效率;
    • 网站数据的备份将会很痛苦。

    此时可能最佳的解决办法是将静态资源路径设置到磁盘的基本个目录。

    Springboot中可以直接在配置文件中覆盖默认的静态资源路径的配置信息:

    • application.properties配置文件如下:
    web.upload-path=E:/jsr_img/
    
    spring.mvc.static-path-pattern=/**
    spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,
      classpath:/static/,classpath:/public/,file:${web.upload-path}

    注意:

     ①web.upload-path这个属于自定义的属性,指定了一个路径,注意要以/结尾;

     ②spring.mvc.static-path-pattern=/**表示所有的访问都经过静态资源路径;

     ③spring.resources.static-locations在这里配置静态资源路径,前面说了这里的配置是覆盖默认配置,所以需要将默认的也加上,否则staticpublic等这些路径将不能被当作静态资源路径,在这里的最末尾加上file:${web.upload-path}之所以要加file:是因为要在这里指定一个具体的硬盘路径,其他的使用classpath指定的是系统环境变量;

    图片上传和访问例子:

    上传图片:

    public int insertImg(MultipartFile file) {
    
        String filename = file.getOriginalFilename();//上传图片的名字
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID().toString();
        filename = name + suffixName;//图片重命名
        String imgFilePath = "E:/jsr_img/";
        String path_img = imgFilePath + filename;//图片存储路径
        //第一次如果没有保存图片的文件夹创建文件夹
        File dest = new File(path_img);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        //将上传文件存储到服务器中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        //图片路径存储到数据库
        VideoImgEntity videoImgEntity=new VideoImgEntity();
        videoImgEntity.setImgPath(filename);
    }

    访问图片:

    http://localhost:端口号/数据库中的图片路径

    其他配置文件:

    spring.http.multipart.enabled=true #默认支持文件上传.

    spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.

    spring.http.multipart.location= # 上传文件的临时目录

    spring.http.multipart.max-file-size=1Mb # 最大支持文件大小

    spring.http.multipart.max-request-size=10Mb # 最大支持请求大小

    转载:http://blog.csdn.net/kilua_way/article/details/54601195

  • 相关阅读:
    bzoj 1217 [HNOI2003]消防局的设立 贪心
    bzoj 1124 [POI2008]枪战Maf 贪心
    bzoj 2525 [Poi2011]Dynamite 二分+树形dp
    搭建SpringMVC+MyBatis开发框架六
    搭建SpringMVC+MyBatis开发框架五
    搭建SpringMVC+MyBatis开发框架四
    搭建SpringMVC+MyBatis开发框架三
    搭建SpringMVC+MyBatis开发框架二
    搭建SpringMVC+MyBatis开发框架一
    Mac下安装Node.js
  • 原文地址:https://www.cnblogs.com/nananana/p/8622468.html
Copyright © 2011-2022 走看看