SpringBoot 打包后(jar包) 实现文件上传

文件上传是一个项目最基础的功能,按道理说应该有不会有多困难,但恶心就恶心在 SpringBoot 最方便的优点上!!!

因为 SpringBoot 是内置 Tomcat 的,所以我们并不需要部署到 Tomcat 的服务器,但当打包后(jar包)就出现了问题。

在 IDE 时,因为是正常的文件目录,所以原来的文件上传功能就可以实现,但是打包后,所有的静态文件都变成了 jar 包!!!

这就很头疼,因为当访问 /static 时,实质上访问的是 jar 包文件内容。

这句需要我们配置一个虚拟路径的配置文件:

package com.csc.portal.boot.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private AppConfig appConfig;
    /**
     * 静态资源处理
     **/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //appConfig.getResPhysicalPath() 这表示项目所在的文件夹,下面会有介绍
        String webPath = appConfig.getResPhysicalPath();

        File file = new File(webPath + "/logistics/");
        if (!file.exists()) {
            file.mkdirs();
        }
        System.out.println("静态资源处理:" + webPath + "/logistics/");

        registry.addResourceHandler("/logistics/**").addResourceLocations("file:" + webPath + "/logistics/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

}
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;

import java.io.File;


@Component
public class AppConfig {
    
    /**
     * 获取项目所在的文件夹
     * @return
     */
    public String getResPhysicalPath(){
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        //项目部署的目录
        if(jarFile != null){
            String path = jarFile.getParentFile().getPath();
            return path;
        }
        return null;
    }
    
}

至此,我们在上传、下载或访问jar包外部的静态资源时,只需调用AppConfig的getResPhysicalPath方法,来获取目录地址。

但在浏览器访问资源时,地址为:http://localhost:8080/logistics/222.jpg 是配置类中文件夹目录

还有一种方式

将打包后的jar包,和自定义的静态文件夹static放在同级目录下,然后使用命令:

java -cp static -jar name.jar

name.jar是自己工程jar包的名字,此时启动后,同样可以实现访问外部的静态资源

获取目录地址,同样使用下面代码:

ApplicationHome home = new ApplicationHome(getClass());
File jarFile = home.getSource();
String path = jarFile.getParentFile().getPath();

path即为项目实际地址

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值