当前位置: 首页 > news >正文

【Spring Boot 3】【Web】返回图片

【Spring Boot 3】【Web】返回图片

  • 背景
  • 介绍
  • 开发环境
  • 开发步骤及源码
  • 工程目录结构

背景

软件开发是一门实践性科学,对大多数人来说,学习一种新技术不是一开始就去深究其原理,而是先从做出一个可工作的DEMO入手。但在我个人学习和工作经历中,每次学习新技术总是要花费或多或少的时间、检索不止一篇资料才能得出一个可工作的DEMO,这占用了我大量的时间精力。因此本文旨在通过一篇文章即能还原出可工作的、甚至可用于生产的DEMO,期望初学者能尽快地迈过0到1的这一步骤,并在此基础上不断深化对相关知识的理解。
为达以上目的,本文会将开发环境、工程目录结构、开发步骤及源码尽量全面地展现出来,文字描述能简则简,能用代码注释的绝不在正文中再啰嗦一遍,正文仅对必要且关键的信息做重点描述。

介绍

本文介绍开发 Spring Boot Web 应用时如何返回图片给前端显示。

开发环境

分类名称版本
操作系统WindowsWindows 11
JDKOracle JDK21.0.1
IDEIntelliJ IDEA2023.3.7
构建工具Apache Maven3.9.9

开发步骤及源码

1> 创建Maven工程,添加依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.jiyongliang</groupId><artifactId>springboot3-web</artifactId><version>0.0.1</version></parent><artifactId>springboot3-web-media</artifactId><properties><java.version>21</java.version><maven.compiler.source>21</maven.compiler.source><maven.compiler.target>21</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring-boot.version>3.3.3</spring-boot.version><lombok.version>1.18.34</lombok.version></properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version><scope>compile</scope></dependency></dependencies><build><pluginManagement><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></pluginManagement></build>
</project>

2> 定义SpringBoot应用启动类。

package com.jiyongliang.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBoot3WebMediaApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot3WebMediaApplication.class, args);}
}

3> 创建测试用图片资源,目录:src/main/resources/images
在这里插入图片描述

4> 创建返回图片的 Controller。

package com.jiyongliang.springboot.controller;import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
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.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;@RestController
@RequestMapping("/image")
@Slf4j
public class ImageController {/*** http://localhost:8080/image/jpg/WARCRAFT.jpg*/@GetMapping("/jpg/{imageName}")public ResponseEntity<FileSystemResource> jpg(@PathVariable(name = "imageName") String imageName) {return getImageAsResource(imageName, MediaType.IMAGE_JPEG);}/*** http://localhost:8080/image/png/wukong.png*/@GetMapping("/png/{imageName}")public ResponseEntity<byte[]> png(@PathVariable(name = "imageName") String imageName) {return getImageAsByteArray(imageName, MediaType.IMAGE_PNG);}private ResponseEntity<FileSystemResource> getImageAsResource(String imageName, MediaType mediaType) {try {File file = ResourceUtils.getFile("classpath:images/" + imageName);FileSystemResource resource = new FileSystemResource(file);return ResponseEntity.ok().contentLength(file.length()).contentType(mediaType).body(resource);} catch (FileNotFoundException e) {log.error("File[{}] is not existed", imageName);return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();}}private ResponseEntity<byte[]> getImageAsByteArray(String imageName, MediaType mediaType) {try {File file = ResourceUtils.getFile("classpath:images/" + imageName);byte[] imageBytes = Files.readAllBytes(file.toPath());return ResponseEntity.ok().contentLength(imageBytes.length).contentType(mediaType).body(imageBytes);} catch (FileNotFoundException e) {log.error("File[{}] is not existed", imageName);return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();} catch (IOException e) {log.error("Unexpected server error: {}", e.getMessage());return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();}}
}

5> 启动应用,使用浏览器测试。

  • http://localhost:8080/image/jpg/WARCRAFT.jpg
  • http://localhost:8080/image/png/wukong.png

工程目录结构

在这里插入图片描述

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Beyond Compare4.2.4 64位OS最新密钥
  • 全球圆柱锂电池行业领军者!比克电池亮相2024深圳eVTOL展
  • Redis:Redis性能变慢的原因
  • Qt (15)【Qt窗口 —— 字体对话框 QFontDialog | 输入对话框 QInputDialog】
  • 【压力测试】如何确定系统最大并发用户数?
  • 超市会员管理系统
  • SQL经典五十道选刷
  • Tushare库:Python金融数据分析的利器
  • 鸿蒙(API 12 Beta6版)图形【 请求动画绘制帧率】方舟2D图形服务
  • Linux开发:优化VSCode C++开发体验
  • 什么酱酒能收藏几十年?快来打造你的私人酒窖宝藏
  • Vue双向绑定
  • 【Linux操作系统】线程的互斥与同步
  • machine learning - 2
  • 【VUE】Vue 组件详解
  • 收藏网友的 源程序下载网
  • [原]深入对比数据科学工具箱:Python和R 非结构化数据的结构化
  • 5、React组件事件详解
  • crontab执行失败的多种原因
  • github从入门到放弃(1)
  • Hibernate最全面试题
  • iOS筛选菜单、分段选择器、导航栏、悬浮窗、转场动画、启动视频等源码
  • LeetCode刷题——29. Divide Two Integers(Part 1靠自己)
  • Python爬虫--- 1.3 BS4库的解析器
  • Service Worker
  • Spring声明式事务管理之一:五大属性分析
  • 分类模型——Logistics Regression
  • 构建二叉树进行数值数组的去重及优化
  • 关于 Linux 进程的 UID、EUID、GID 和 EGID
  • 聚簇索引和非聚簇索引
  • 写给高年级小学生看的《Bash 指南》
  • 优秀架构师必须掌握的架构思维
  • NLPIR智能语义技术让大数据挖掘更简单
  • ​LeetCode解法汇总2182. 构造限制重复的字符串
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • !!Dom4j 学习笔记
  • #我与Java虚拟机的故事#连载16:打开Java世界大门的钥匙
  • (09)Hive——CTE 公共表达式
  • (2)nginx 安装、启停
  • (2)从源码角度聊聊Jetpack Navigator的工作流程
  • (3)(3.5) 遥测无线电区域条例
  • (31)对象的克隆
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (补充):java各种进制、原码、反码、补码和文本、图像、音频在计算机中的存储方式
  • (分布式缓存)Redis持久化
  • (附源码)springboot掌上博客系统 毕业设计063131
  • (附源码)ssm考生评分系统 毕业设计 071114
  • (七)Appdesigner-初步入门及常用组件的使用方法说明
  • (三)uboot源码分析
  • (三维重建学习)已有位姿放入colmap和3D Gaussian Splatting训练
  • (学习日记)2024.03.12:UCOSIII第十四节:时基列表
  • (转)linux下的时间函数使用
  • (转载)hibernate缓存
  • (转载)Linux网络编程入门
  • (转载)从 Java 代码到 Java 堆