Java怎么定义图片公共路径_【Java】springboot配置图片访问路径

springboot如何配置,就可以在地址栏输入http://localhost:9090/17AD93E86EB44287BA0D871A37017597.jpg就可以访问到图片

2806a84b185ef1aaeb4dea6bd51ac3a6.png

回答

需要添加下Springboot访问静态资源的Jar文件

org.springframework.boot

spring-boot-starter-thymeleaf

直接去掉这两个配置就行,自动已经映射了,这个目录本来就是静态资源部署目录

我之前做文件上传的时候也想上传到项目resources下,可以上传上去,但是不能通过这样的URL访问到。

琢磨了半天,好像是因为SpringBoot项目启动之后,它会在C盘的C:\Users\User\AppData\Local\Temp这个文件夹内创建一个新的服务器,每次重启都会创建,所以每次重启之后,就相当于是在一个新的服务器上部署了项目,之前上传的文件都在另外一个服务器上,所以文件都没有了。。。。重新上传。

c31c54da87c409988eb5482ec2899695.png

这是我的代码:

private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("\\yyyy\\MM\\dd");

public JsonResult uploadFile(MultipartFile file, HttpServletRequest request) {

//1.获取项目根路径,结果是:C:\Users\User\AppData\Local\Temp\tomcat-docbase.766171933481555296.8081,File.separator是系统分隔符

String rootPath = request.getSession().getServletContext().getRealPath(File.separator);

//2.拼接目录,结果是: /images/2020/03/15

String directory = "\\images" + simpleDateFormat.format(new Date());

//3.现在目录可能还不存在,创建目录(全路径的目录),FileUtil是自定义的工具

FileUtil.createDir(rootPath + directory);

//4.给文件重新设置一个名字

String newFileName = FileUtil.getNewFileName(file.getOriginalFilename());

//5.创建这个新文件

File newFile = new File(rootPath + directory + "\\" + newFileName);

//6.复制操作

try {

file.transferTo(newFile);

//文件在服务器上的保存位置格式:/images/2020/03/22/asd45~~~~asdqwe.jpg

String fileName = directory + File.separator + newFileName;

//可通过此路径fileAllPath在浏览器访问 协议 地址 端口号 目录(/images/2020/03/15) 文件名

String fileAllPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + directory + "\\" + newFileName;

HashMap map = new HashMap<>(2);

map.put("fileName", fileName);

map.put("fileAllPath", fileAllPath);

return JsonResult.builder().data(map).message("上传成功!").code("1").build();

} catch (IOException e) {

return JsonResult.builder().data(null).message("IO异常!").code("-1").build();

}

}

在上面代码中fileAllPath就是可以直接在浏览器上访问的URL

工具类创建目录的方法:

public static boolean createDir(String destDirName) {

File dir = new File(destDirName);

if (dir.exists()) {

return false;

}

//如果结尾没有文件分隔符

if (!destDirName.endsWith(File.separator)) {

destDirName += File.separator;

}

//创建单个目录

return dir.mkdirs();

}

目前我还没发现可以上传到你说的这个位置并且可以访问的方法,针对重启就没有了之前上传的文件的解决方法:

用图片服务器

项目打成war包,放在自己的tomcat服务器里面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值