在 Spring Boot 中,您可以通过以下步骤实现图片批量传输给前端:

  1. 创建 'static' 文件夹:在您的 Spring Boot 项目的 'resources' 目录下创建一个名为 'static' 的文件夹,用于存放图片文件。

  2. 将图片放入文件夹:将您需要传输的图片文件放入 'static' 文件夹中。

  3. 创建 Controller 接口:在您的 Spring Boot 项目中创建一个 Controller 类,并定义一个接口用于获取图片文件路径。

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;

@RestController
@RequestMapping("/images")
public class ImageController {

    @GetMapping("/{filename}")
    public ResponseEntity<byte[]> getImage(@PathVariable("filename") String filename) throws IOException {
        Resource resource = new ClassPathResource("static/" + filename);
        byte[] imageBytes = Files.readAllBytes(resource.getFile().toPath());
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(imageBytes);
    }
}
  1. 前端页面显示图片:在您的前端页面中,使用该接口获取图片文件的路径,并将图片显示出来。
<img src="/images/{filename}" alt="image">

其中 {filename} 是具体的图片文件名。

当访问 /images/{filename} 接口时,将返回对应图片文件的字节数组,并设置响应头的 Content-Type 为 image/jpeg,前端页面会根据该响应内容显示图片。

请确保图片文件存在于 'static' 文件夹中,并且文件名在前端页面中正确指定。

Spring Boot 批量图片传输给前端 -  详细教程

原文地址: https://www.cveoy.top/t/topic/p2pY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录