springboot 静态资源访问,和文件上传 ,以及路径问题

springboot 静态资源访问:

 这是springboot 默认的静态资源访问路径  访问顺序依次从前到后(http://localhost:8080/bb.jpg)

spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/   

 

 

自定义静态资源访问路径 (http://localhost:8080/bb.jpg)

# 静态文件请求匹配方式 (只要是请求路径配到到了 就访问下面配置的默认静态资源路径)
spring.mvc.static-path-pattern=/**
# 修改默认的静态寻址资源目录 多个使用逗号分隔
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/upload/

//自定义 不在项目下的路径(比如: c:/upload2)  通过http://localhost:8080/bb.jpg 也能访问  记得加配置

# 静态文件请求匹配方式 (只要是请求路径配到到了 就访问下面配置的默认静态资源路径)
spring.mvc.static-path-pattern=/**
# 修改默认的静态寻址资源目录 多个使用逗号分隔
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/upload/,classpath:/ c:/upload2

springboot  实现多文件上传

 对于上传路径问题  可以通过上面讲的自定义路径来进行配置:下载到电脑的某个位置然后进行访问 和上面的配置一模一样 只是classpath=>file

web.upload-path=/Users/jack/Desktop
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}

下面贴代码:(文件下载到tomcate下)

 html:

<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="head_img"/>
姓名:<input type="text" name="name"/>
<input type="submit" value="上传"/>
</form>

</body>

下载工具类:
/**
* 提取上传方法为公共方法
* @param uploadDir 上传文件目录
* @param file 上传对象
* @throws Exception
*/
private void executeUpload(String uploadDir,MultipartFile file) throws Exception
{
//文件后缀名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//上传文件名
String filename = UUID.randomUUID() + suffix;
//服务器端保存的文件对象
File serverFile = new File(uploadDir + filename);
//将上传的文件写入到服务器端文件内
file.transferTo(serverFile);
}

controller:
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
public @ResponseBody String uploads(HttpServletRequest request,MultipartFile[] file)
{
try {
//上传目录地址
// 随意 String uploadDir = C:/img/;
String uploadDir=ResourceUtils.getURL("classpath:").getPath()+"/static/up/";
System.out.println(uploadDir);
//如果目录不存在,自动创建文件夹
File dir = new File(uploadDir);
if(!dir.exists())
{
dir.mkdir();
}
//遍历文件数组执行上传
for (int i =0;i<file.length;i++) {
if(file[i] != null) {
//调用上传方法
executeUpload(uploadDir, file[i]);
}
}
}catch (Exception e)
{
//打印错误堆栈信息
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}

 然后文件下载路径就到了tomcate 下。

需要配置

web.upload-path=/C:/img/
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/,file:${web.upload-path},file:/static/

也可以通过 http://localhost:8080/up/bb.jpg 访问

 

posted @ 2019-01-22 15:39  好记性不如烂笔头=>  阅读(35184)  评论(0编辑  收藏  举报