在Spring Boot WebFlux中,可以使用`Mono<byte[]>`或`Flux<byte[]>`作为响应体来返回字节流。以下是一个简单的示例:
1. 首先,添加WebFlux依赖到`pom.xml`文件中:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
```
2. 创建一个控制器类,如下所示:
```java
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@RestController
public class ByteStreamController {
@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public Mono<ResponseEntity<ByteArrayResource>> download() {
String content = "Hello, World!";
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(bytes);
return Mono.just(ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=test.txt")
.contentLength(bytes.length)
.body(resource));
}
}
```
在这个示例中,我们创建了一个名为`ByteStreamController`的控制器类,其中包含一个名为`download`的方法。该方法使用`@GetMapping`注解映射到`/download`路径,并指定响应的媒体类型为`application/octet-stream`。方法返回一个`Mono<ResponseEntity<ByteArrayResource>>`对象,其中包含要下载的文件内容。