当前位置: 代码网 > it编程>编程语言>Java > 基于SpringBoot框架实现文件上传下载分享功能

基于SpringBoot框架实现文件上传下载分享功能

2025年06月08日 Java 我要评论
springboot 文件上传下载是我们常用的功能,比如图片、视频上传、下载和更新等功能的实现。下面我们详细分析一下:1、pom.xml包引入<!-- 基础 web 依赖(包含文件上传支持)

springboot 文件上传下载是我们常用的功能,比如图片、视频上传、下载和更新等功能的实现。下面我们详细分析一下:

1、pom.xml包引入

<!-- 基础 web 依赖(包含文件上传支持)  -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>
 
<!-- 文件操作工具类 -->
<dependency>
    <groupid>commons-io</groupid>
    <artifactid>commons-io</artifactid>
    <version>2.11.0</version>
</dependency>

2、存储目录设计

/data/project_files/
    ├── images/
    │   ├── 202405/
    │   └── 202406/
    └── videos/
        ├── 202405/
        └── 202406/
  • 使用 uuid 生成唯一文件名(保留原始扩展名)
  • 按年月生成子目录(防止单目录文件过多)
  • 推荐存储绝对路径到数据库(如:/images/202405/uuid123.jpg)

3、配置文件信息

# win环境文件存储根目录 
file.upload-dir=d:/data/project_files/
 
#linux环境
file.upload-dir=/data/project_files/
 
# 上传大小限制(默认1mb,按需调整) 
spring.servlet.multipart.max-file-size=100mb
spring.servlet.multipart.max-request-size=100mb

4、上传接口

@postmapping("/upload")
public apiresult uploadfile(@requestparam("file") multipartfile file, 
                               @requestparam string filetype) throws ioexception {
        // 验证文件类型
        if (!arrays.aslist("image", "video").contains(filetype)) {
            return apiresult.error("invalid file type");
        }
 
        // 生成存储路径
        string datepath = localdate.now().format(datetimeformatter.ofpattern("yyyymm"));
        string fileext = filenameutils.getextension(file.getoriginalfilename());
        string uuid = uuid.randomuuid().tostring();
        string relativepath = string.format("/%s/%s/%s.%s", 
            filetype + "s", datepath, uuid, fileext);
        
        // 保存文件
        file dest = new file(uploaddir + relativepath);
        fileutils.forcemkdirparent(dest);
        file.transferto(dest);
 
        return apiresult.ok(relativepath);
    }

直接获取下载地址上传方式

    @postmapping("/uploadfile")
    @apioperation(value="文件上传",notes = "文件上传-√")
    public string uploadfile(@requestparam("file")multipartfile file, @requestparam string filetype) throws ioexception {
        // 验证文件类型
        if (!arrays.aslist("image", "video").contains(filetype)) {
            return commonresponse.builderrorresponse("error file type");
        }
        // 生成存储路径
        string datepath = localdate.now().format(datetimeformatter.ofpattern("yyyymm"));
        string fileext = filenameutils.getextension(file.getoriginalfilename());
        string uuid = uuid.randomuuid().tostring();
        string relativepath = string.format("/%s/%s/%s.%s",
                filetype + "s", datepath, uuid, fileext);
 
        // 保存文件
        file dest = new file(uploaddir + relativepath);
        fileutils.forcemkdirparent(dest);
        file.transferto(dest);
        log.info("filepath:{}",fileipporturl+relativepath);
        return (fileipporturl+relativepath);
    }

5、下载接口

1)接口下载

 @getmapping("/download")
    public responseentity<resource> downloadfile(@requestparam string filepath) throws ioexception {
        path path = paths.get(uploaddir + filepath);
        resource resource = new urlresource(path.touri());
        
        return responseentity.ok()
                .header(httpheaders.content_disposition, 
                    "attachment; filename=\"" + resource.getfilename() + "\"")
                .body(resource);
    }

2)原路径获取下载

    @getmapping("/download/**")
    @apioperation(value="文件下载接口",notes = "文件下载接口-√")
    public responseentity<resource> downloadfile(httpservletrequest request) throws ioexception {
        // 获取完整文件路径(需截掉前缀路径)
        string filepath = request.getservletpath()
                .replacefirst("/file/******/", "");
        log.info("filepath:{}",filepath);
        // 路径安全校验
        if (filepath.contains("..")) {
            return responseentity.badrequest().build();
        }
 
        path path = paths.get(uploaddir + file.separator + filepath);
        log.info("path:{}",path);
        resource resource = new urlresource(path.touri());
        log.info("touri:{}",path.touri());
        if (!resource.exists()) {
            return responseentity.notfound().build();
        }
 
        return responseentity.ok()
                .header(httpheaders.content_disposition,
                        "attachment; filename=\"" + resource.getfilename() + "\"")
                .body(resource);
    }

 6、修改文件

    @postmapping("/update")
    public apiresult updatefile(@requestparam("file") multipartfile file,
                               @requestparam string oldfilepath) throws ioexception {
        // 删除旧文件
        file oldfile = new file(uploaddir + oldfilepath);
        if (oldfile.exists()) {
            fileutils.forcedelete(oldfile);
        }
        
        // 上传新文件(复用上传逻辑)
        return uploadfile(file, parsefiletype(oldfilepath));
    }

或者

    
 
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.value;
import org.springframework.core.io.resource;
import org.springframework.core.io.urlresource;
import org.springframework.http.httpheaders;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.multipartfile;
import org.apache.commons.io.fileutils;
import org.apache.commons.io.filenameutils;
 
import javax.servlet.http.httpservletrequest;
import java.io.file;
import java.io.ioexception;
import java.nio.file.path;
import java.nio.file.paths;
import java.time.localdate;
import java.time.format.datetimeformatter;
import java.util.arrays;
import java.util.uuid;
 
 
 
 
   @postmapping("/update")
    public string updatefile(@requestparam("file") multipartfile file,
                                @requestparam string oldfilepath, @requestparam string filetype) throws ioexception {
        // 删除旧文件
        file oldfile = new file(uploaddir + oldfilepath);
        if (oldfile.exists()) {
            fileutils.forcedelete(oldfile);
        }
        // 上传新文件(复用上传逻辑)
        return uploadfile(file, filetype);
    }

到此,文件上传下载分享完成。

到此这篇关于基于springboot框架实现文件上传下载分享功能的文章就介绍到这了,更多相关springboot文件上传下载分享内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com