【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;
    }
posted @ 2018-02-06 18:13  SEC.VIP_网络安全服务  阅读(459)  评论(0编辑  收藏  举报