36.md 8.4 KB
Newer Older
W
wizardforcel 已提交
1
# 在 Spring Boot 中提供图像文件
W
wizardforcel 已提交
2 3 4

> 原文: [http://zetcode.com/articles/springbootserveimage/](http://zetcode.com/articles/springbootserveimage/)

W
wizardforcel 已提交
5
在本教程中,我们展示了如何在 Spring Boot RESTful Web 应用中提供图像文件。 该图像是位于资源目​​录中的 JPEG 文件。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
Spring 是用于开发 Java 企业应用的 Java 应用框架。 它还有助于集成各种企业组件。 Spring Boot 使创建具有 Spring 动力的生产级应用和服务变得很容易,而对安装的要求却最低。
W
wizardforcel 已提交
8 9 10

我们将展示将图像数据发送到客户端的三种方式。

W
wizardforcel 已提交
11
## Spring 图像示例
W
wizardforcel 已提交
12

W
wizardforcel 已提交
13
该 Web 应用在`src/main/resources/image`目录中包含一个`sid.jpg`文件。 `ClassPathResource`用于获取图像文件。
W
wizardforcel 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

```java
pom.xml
src
├── main
   ├── java
      └── com
          └── zetcode
              ├── Application.java
              └── controller
                  └── MyController.java
   └── resources
       └── image
           └── sid.jpg
└── test
    └── java

```

这是项目结构。

`pom.xml`

```java
<?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>

    <groupId>com.zetcode</groupId>
    <artifactId>springimage</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

```

W
wizardforcel 已提交
84
这是 Maven 构建文件。 Spring Boot 启动器是一组有用的依赖项描述符,可大大简化 Maven 配置。 `spring-boot-starter-parent`具有 Spring Boot 应用的一些常用配置。 `spring-boot-starter-web`是使用 Spring MVC 构建 Web 应用的入门工具。 它使用 Tomcat 作为默认的嵌入式服务器。 `spring-boot-maven-plugin`在 Maven 中提供了 Spring Boot 支持,使我们可以打包可执行的 JAR 或 WAR 档案。 它的`spring-boot:run`目标执行 Spring Boot 应用。
W
wizardforcel 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

`com/zetcode/Application.java`

```java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

```

W
wizardforcel 已提交
104
`Application`设置 Spring Boot 应用。 `@SpringBootApplication`启用组件扫描和自动配置。
W
wizardforcel 已提交
105

W
wizardforcel 已提交
106
### 使用`HttpServletResponse`提供图像
W
wizardforcel 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

在第一种情况下,我们直接写入`HttpServletResponse`

`com/zetcode/controller/MyController.java`

```java
package com.zetcode.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @RequestMapping(value = "/sid", method = RequestMethod.GET,
            produces = MediaType.IMAGE_JPEG_VALUE)

    public void getImage(HttpServletResponse response) throws IOException {

        var imgFile = new ClassPathResource("image/sid.jpg");

        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
    }
}

```

在此控制器中,我们获取图像资源并将其直接写入响应对象。

```java
var imgFile = new ClassPathResource("image/sid.jpg");

```

W
wizardforcel 已提交
148
我们从类路径与`ClassPathResource`图片资源中(`src/main/resource`是在 Java 类路径)。
W
wizardforcel 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

```java
response.setContentType(MediaType.IMAGE_JPEG_VALUE);

```

响应的内容类型设置为`MediaType.IMAGE_JPEG_VALUE`

```java
StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());

```

使用`StreamUtils`,我们将数据从图像复制到响应对象。

W
wizardforcel 已提交
164
### 用`ResponseEntity`提供图像
W
wizardforcel 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

在第二种情况下,我们使用`ResponseEntity`

`com/zetcode/controller/MyController.java`

```java
package com.zetcode.controller;

import java.io.IOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @RequestMapping(value = "/sid", method = RequestMethod.GET,
            produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<byte[]> getImage() throws IOException {

        var imgFile = new ClassPathResource("image/sid.jpg");
        byte[] bytes = StreamUtils.copyToByteArray(imgFile.getInputStream());

        return ResponseEntity
                .ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(bytes);
    }
}

```

W
wizardforcel 已提交
201
`getImage()`方法的返回类型设置为`ResponseEntity<byte[]>`
W
wizardforcel 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

```java
byte[] bytes = StreamUtils.copyToByteArray(imgFile.getInputStream());

```

使用`StreamUtils.copyToByteArray()`,我们将图像数据复制到字节数组中。

```java
return ResponseEntity
        .ok()
        .contentType(MediaType.IMAGE_JPEG)
        .body(bytes);

```

字节数组提供给`ResponseEntity`的主体。

W
wizardforcel 已提交
220
### 使用`ResponseEntity`和`InputStreamResource`提供图像
W
wizardforcel 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

在第三种情况下,我们使用`ResponseEntity``InputStreamResource``InputStreamResource`是 Spring 对低级资源的抽象。

`com/zetcode/controller/MyController.java`

```java
package com.zetcode.controller;

import java.io.IOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @RequestMapping(value = "/sid", method = RequestMethod.GET,
            produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<InputStreamResource> getImage() throws IOException {

        var imgFile = new ClassPathResource("image/sid.jpg");

        return ResponseEntity
                .ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(new InputStreamResource(imgFile.getInputStream()));
    }
}

```

W
wizardforcel 已提交
256
`getImage()`方法的返回类型设置为`ResponseEntity<InputStreamResource>`
W
wizardforcel 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

```java
return ResponseEntity
        .ok()
        .contentType(MediaType.IMAGE_JPEG)
        .body(new InputStreamResource(imgFile.getInputStream()));

```

`ResponseEntity`的主体返回`InputStreamResource`

```java
$ mvn spring-boot:run

```

W
wizardforcel 已提交
273
我们启动 Spring Boot 应用。
W
wizardforcel 已提交
274 275 276

我们导航到`http://localhost:8080/sid`在浏览器中显示图像。

W
wizardforcel 已提交
277
在本教程中,我们展示了如何从 Spring Boot 应用向客户端发送图像数据。 我们使用了三种不同的方法。 您可能也对这些相关教程感兴趣:[用 Java 显示图像](/java/displayimage/)[Java 教程](/lang/java/)或列出[所有 Spring Boot 教程](/all/#springboot)