SpringBoot上传文件到本服务器 目录与jar包同级问题
目录
- 前言
- 原因
- 实现
- 不要忘记
- 最后的封装
- Follow up
| 1 2 |
ClassPathResource classPathResource = new ClassPathResource("static/a.txt");
classPathResource.getInputStream();
|
其中,这个a.txt存放在resources/static目录下
通过上述方式可以获取a中的内容
?| 1 2 3 4 |
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) {
path = new File("");
}
|
然后获取需要的目录,我们设定我们需要将文件存放在与jar包同级的static的upload目录下
?| 1 2 3 4 |
File upload = new File(path.getAbsolutePath(),"static/upload/");
if(!upload.exists()) {
upload.mkdirs();
}
|
然后当我们要将上传的文件存储的时候,按照下面的方式去新建文件,然后使用你喜欢的方式进行存储就可以了。
?| 1 2 |
File upload = new File(path.getAbsolutePath(),"static/upload/test.jpg");
FileUtils.copyInputStreamToFile(inputStream, uploadFile);
|
| 1 2 3 4 |
spring:
# 静态资源路径
resources:
static-locations: classpath:static/,file:static/
|
这样就能实现上传文件
https://github.com/LinkinStars/springBootTemplate/blob/master/src/main/java/com/linkinstars/springBootTemplate/util/FileHandleUtil.java这个工具类依赖了
?| 1 2 |
compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.1'
compile group: 'commons-io', name: 'commons-io', version: '2.4'
|
如何你不喜欢完全可以根据自己的喜欢改变
如何使用:
?| 1 2 3 4 5 6 7 8 |
/**
* 测试文件上传
*/
@RequestMapping("/upload")
@ResponseBody
public String upload(MultipartFile file) throws IOException {
return "文件存放路径为" + FileHandleUtil.upload(file.getInputStream(), "image/", file.getOriginalFilename());
}
|
最后效果

Follow up
这个工具类只是实现了如何上传文件,入参也只有InputStream,后续如何你需要接入参数File或者加入文件名防重复等等,就由你来完成了。
总结
以上所述是小编给大家介绍的SpringBoot上传文件到本服务器 目录与jar包同级问题,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!