标签:vue resource springboot imageData static file path uuid
如果你满足以下条件,则可以继续往下看:
- 前端使用vue并且想使用url访问图片资源
- 后端使用springboot并且想把图片资源存储在resource下
后端配置
#application.yml
#借鉴地址: https://blog.csdn.net/lorogy/article/details/103918934
spring:
# 映射resource.static下文件,使之可以通过url地址直接访问
mvc:
static-path-pattern: /**
@RequestMapping(value = "/uploadFile")
public R uploadFile(MultipartFile file, HttpServletRequest request) {
if (file.isEmpty()) {
return R.error("图片文件为空");
}
String uuid;
try{
//上传
byte[] bytes = file.getBytes();
String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
uuid = UUID.randomUUID().toString()+fileSuffix;
Integer length = getClass().getClassLoader().getResource("static/imageData/resource.txt").toString().length();
String resourcePath = getClass().getClassLoader().getResource("static/imageData/resource.txt").toString().substring(6, length - 12);
log.info("地址为:" + resourcePath);
Path path = Paths.get(resourcePath + uuid);
path.toFile().getParentFile().mkdirs();
path.toFile().createNewFile();
Files.write(path, bytes);
}catch(Exception e) {
e.printStackTrace();
return R.error("上传失败");
}
return R.ok("上传成功").put("address", uuid);
}
!!!最重要的(这里一定要创建imageData文件夹,并且创建resource.txt文件) ------imageData和resource.txt的名字可以随意更改,但是需要对应起来
解释说明: 之前找了大量资料,没办法自动获取resource下的路径,基本上手动写url的多一些,但是开发环境和线上环境的地址又不同,就很麻烦
解决办法: 通过getClass().getClassLoader().getResource()可以获取文件的绝对路径,而且还是自动的
浏览器访问
#示例
localhost:8001/imageData/9d1f3a13-5eb0-4b24-8a8c-ff20bb07ec31.jfif
#格式
后端接口地址/imageData/xxxx.xx
标签:vue,resource,springboot,imageData,static,file,path,uuid 来源: https://blog.csdn.net/qq_39820568/article/details/115286347
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。