springboot里面关于文件上传路径和服务器开放路径的代码写法

前端传来文件/流/base64字符串.
后端需要对其进行保存
(1)保存需要一个服务器本地磁盘的路径,
本地磁盘的话需要动态的去项目的同级目录去新建一个文件夹来保存
目的是保存

 public static String getSavePath() throws FileNotFoundException {
        // 项目路径
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists())
            path = new File("");
        // 绝对路径=项目路径+自定义路径
        File upload = new File(path.getAbsolutePath(), "static/pic/");
        if (!upload.exists())
            upload.mkdirs();
        System.err.println("path1::" + upload.getAbsolutePath());//path1是正常的,和src同级
        // 绝对路径=项目路径+打包的
//        String path2 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//        System.err.println("path2"+path2);//path2的中文是乱码,/target/classes/
        return upload.getAbsolutePath();
    }

后面再拼写下.jpg就好了

(2)也需要一个服务器url路径
也要求要动态地获取
目的是给前端访问

@Component
public class ServerAddressAndPort implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;

    public String getUrl() throws UnknownHostException {
        InetAddress address = null;
        address = InetAddress.getLocalHost();
        return "http://" + address.getHostAddress() + ":" + this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

}

同样,后面拼写下.jpg就好了

springmvc配置静态访问资源

spring:
  mvc:
    static-path-pattern: /**
  resources:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,\
      classpath:/static/static/,classpath:/static/,classpath:/public/,file:${web.upload-path},file:./static/pic/

file:./static/pic/ 代表项目的同级目录,这种是相对路径的写法
file:xxx/xxx/xxx,这种是绝对路径的写法
这边的要点:static-locations覆盖默认的静态资源路径的配置信息,因此要重新补上去原有配置的静态路径才可以

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值