springboot项目文件上传到服务器本机,返回访问地址

文件上传到服务器本机,然后给出访问地址:

具体如下:

1、添加必要的工具类依赖

XML 复制代码
        <!-- 文件上传工具类 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.18.0</version>
        </dependency>

2、新增配置

1️⃣新增yml相关配置

文件保存位置:

XML 复制代码
# 文件相关
file:
  #后台服务模型目录
  modelPath: D:/home/software/data/upload/

2️⃣新增访问映射配置

java 复制代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 通用配置
 *
 * @author xjs
 */
@Configuration
public class WebResourcesConfig implements WebMvcConfigurer {


    /**
     * 上传文件夹
     */
    @Value("${file.modelPath}")
    private String uploadedFolder;

    /**
     * 添加资源处理程序
     *
     * @param registry 注册表
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 配置资源映射
         * 意思是:如果访问的资源路径是以"/model/"开头的,
         * 就映射到本机的"D:/home/software/data/upload/"这个文件夹内,然后访问资源
         * 注意:D:/home/software/data/upload/ 地址后面的 / 必须添加
         */
        registry.addResourceHandler("/model/**")
                .addResourceLocations("file:" + uploadedFolder);
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilters() {
        CorsConfiguration config = new CorsConfiguration();
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径,拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }
}

3、具体代码实现

java 复制代码
    /**
     * 上传文件夹
     */
    @Value("${file.modelPath}")
    private String uploadedFolder;

    @ApiOperation("上传文件-返回访问地址")
    @PostMapping("/uploadFiles")
    public ResponseEntity<Object> uploadFiles(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        // 获取当前时间
        Date nowDate = new Date( );
        // 定义日期格式
        SimpleDateFormat ftDdy = new SimpleDateFormat ("yyyy/MM/dd");
        // 定义时间格式
        SimpleDateFormat ftTime = new SimpleDateFormat ("HHmmss");

        // 创建一个HashMap用于存储文件信息
        HashMap<String, Object> map = new HashMap<>();
        // 判断文件是否为空
        if (file.isEmpty()) {
            // 如果文件为空,返回错误信息
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件不能为空!");
        }
        // 获取当前日期
        String directory = ftDdy.format(nowDate);
        // 获取当前时间
        String fileNames = ftTime.format(nowDate) + "_" + file.getOriginalFilename();
        // 打印文件名称
        log.info("文件名称: {}", fileNames);
        // 获取目标目录
        String targetDir = Paths.get(uploadedFolder, directory).toString();
        // 打印目标目录
        log.info("目标目录: {}", targetDir);
        // 创建目标目录
        createDirectoriesIfNotExists(targetDir);
        // 将文件名称和原始文件名称存入map
        map.put("newFileName", fileNames);
        map.put("originalFilename", file.getOriginalFilename());
        try {
            // 将文件保存到目标目录
            file.transferTo(Paths.get(targetDir, fileNames));
            // 将文件路径存入map
            map.put("filePath", targetDir + "\\" + fileNames);
            //http 协议 ://127.0.0.1 ip地址 :18080 端口号 / 文件目录(/model/2025/04/30/xxx.xxx)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/model/" + directory + "/" + fileNames;
            log.info("文件上传,访问URL:" + url);
            map.put("url", url);
            return ResponseEntity.status(HttpStatus.OK).body(map);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败!");
        }
    }

4、实现上传

结果返回

bash 复制代码
{
    "filePath": "D:\\home\\software\\data\\upload\\2025\\04\\28\\110940_RC.gif",
    "newFileName": "110940_RC.gif",
    "originalFilename": "RC.gif",
    "url": "http://192.168.5.88:18080/model/2025/04/28/110940_RC.gif"
}

然后即可在浏览器中访问url地址

至此即可实现上传获取访问地址!

相关推荐
潘yi.7 分钟前
web技术与nginx网站环境部署
服务器·网络·nginx
安顾里32 分钟前
Linux命令-iostat
linux·运维·服务器
whoarethenext36 分钟前
初始https附带c/c++源码使用curl库调用
服务器·c++·qt·https·curl
100编程朱老师1 小时前
面试:什么叫Linux多路复用 ?
linux·运维·服务器
群联云防护小杜1 小时前
云服务器主动防御策略与自动化防护(下)
运维·服务器·分布式·安全·自动化·音视频
Jtti1 小时前
Jtti:nginx服务器如何限制访问频率
服务器·网络·nginx
此木|西贝1 小时前
【设计模式】享元模式
java·设计模式·享元模式
struggle20252 小时前
LinuxAgent开源程序是一款智能运维助手,通过接入 DeepSeek API 实现对 Linux 终端的自然语言控制,帮助用户更高效地进行系统运维工作
linux·运维·服务器·人工智能·自动化·deepseek
李少兄2 小时前
解决Spring Boot多模块自动配置失效问题
java·spring boot·后端