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

您所在的位置:网站首页 java上传文件到服务器,路径问题 SpringBoot 打包后(jar包) 实现文件上传

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

2024-06-20 22:12| 来源: 网络整理| 查看: 265

文件上传是一个项目最基础的功能,按道理说应该有不会有多困难,但恶心就恶心在 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即为项目实际地址



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3