欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

Spring Boot应用实现图片资源服务的方法

2025年08月20日 Java
在这篇文章中,我们将介绍如何使用spring boot创建一个rest api来提供服务器上的静态图片资源。该api包括路径安全检查、文件存在性验证以及缓存控制等功能,并且代码包含详细的注释以帮助理解

在这篇文章中,我们将介绍如何使用spring boot创建一个rest api来提供服务器上的静态图片资源。该api包括路径安全检查、文件存在性验证以及缓存控制等功能,并且代码包含详细的注释以帮助理解。

maven依赖

首先,在您的pom.xml文件中添加以下依赖项:

<dependencies>
    <!-- spring boot starter web for building web applications -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- lombok to reduce boilerplate code -->
    <dependency>
        <groupid>org.projectlombok</groupid>
        <artifactid>lombok</artifactid>
        <scope>provided</scope>
    </dependency>
    <!-- for logging -->
    <dependency>
        <groupid>org.slf4j</groupid>
        <artifactid>slf4j-api</artifactid>
    </dependency>
</dependencies>

确保您已经正确配置了maven项目的其他部分,如<parent>标签和版本管理等。

java代码

接下来是核心java代码,位于package pub.qingyun.web;包下:

package pub.qingyun.web;
import lombok.extern.slf4j.slf4j;
import org.springframework.core.io.urlresource;
import org.springframework.http.httpheaders;
import org.springframework.http.mediatype;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.crossorigin;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
import java.net.malformedurlexception;
import java.nio.file.files;
import java.nio.file.path;
import java.nio.file.paths;
@restcontroller
@crossorigin
@slf4j
public class imagecontroller {
    // 图片根目录
    private static final path image_root = paths.get("f:", "temp").toabsolutepath().normalize();
    /**
     * 获取图片资源并返回给客户端
     *
     * @param imagepath 图片文件的相对路径参数
     * @return responseentity<urlresource> 包含图片资源的响应实体,包含适当的http状态码和响应头
     */
    @getmapping("/showimage")
    public responseentity<urlresource> getimage(@requestparam string imagepath) {
        long start = system.currenttimemillis();
        // 参数校验:检查图片路径是否为空
        if (imagepath == null || imagepath.trim().isempty()) {
            log.warn("missing imagepath parameter");
            return responseentity.badrequest().build();
        }
        // 路径安全检查:防止路径遍历攻击
        // 过滤非法字符,防止路径穿越
        if (imagepath.contains("..") || imagepath.contains("\\") || imagepath.startswith("/")) {
            log.warn("forbidden path access attempt: [path_redacted]");
            return responseentity.status(403).build();
        }
        path resolvedpath = image_root.resolve(imagepath).normalize();
        if (!resolvedpath.startswith(image_root)) {
            log.warn("forbidden path access attempt: [path_redacted]");
            return responseentity.status(403).build();
        }
        // 文件存在性检查:验证文件是否存在且为常规文件
        if (!files.exists(resolvedpath) || !files.isregularfile(resolvedpath)) {
            log.info("image not found: [path_redacted]");
            return responseentity.notfound().build();
        }
        // 缓存文件长度,避免重复调用
        long filelength = resolvedpath.tofile().length();
        // 创建资源对象
        urlresource resource;
        try {
            resource = new urlresource(resolvedpath.touri());
        } catch (malformedurlexception e) {
            log.error("failed to create resource for: [path_redacted], malformed url", e);
            return responseentity.status(500).build();
        } catch (exception e) {
            log.error("failed to create resource for: [path_redacted]", e);
            return responseentity.status(500).build();
        }
        // 设置响应头信息
        httpheaders headers = new httpheaders();
        headers.setcachecontrol("public, max-age=86400"); // 缓存 1 天
        headers.setexpires(system.currenttimemillis() + 86400_000l); // 过期时间
        headers.setcontentdispositionformdata("inline", resource.getfilename());
        log.info("getimage [path_redacted] ({} bytes) cost: {}ms", filelength, (system.currenttimemillis() - start));
        // 构建并返回成功响应
        return responseentity.ok()
                .headers(headers)
                .contenttype(mediatype.image_jpeg)
                .contentlength(filelength)
                .body(resource);
    }
}

这个代码段展示了一个简单的spring boot rest控制器,用于从指定路径加载图片并将其作为资源返回给客户端。它包括必要的安全措施来防止潜在的路径遍历攻击,并设置了缓存控制头以提高性能。希望这段代码能为您提供构建自己的图片服务的帮助!

到此这篇关于spring boot应用实现图片资源服务的文章就介绍到这了,更多相关spring boot图片资源服务内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!